intellij idea中快速抽取方法


Intellij Idea使用教程匯總篇

問題:有時候一個方法里面嵌套了很多邏輯,想拆分為多個方法方便調用;或者一個方法復用性很高,這時,這個方法嵌套在局部方法里面肯定是不方便的,如何快速抽取出這個方法?

  1. public class Demo {  
  2.     private static void getInfo(Object obj) {  
  3.         Class<?> clazz = obj.getClass();  
  4.         Method[] methods = clazz.getMethods();  
  5.         for (Method method : methods) {  
  6.             String name = method.getName();  
  7.             Class<?> returnType = method.getReturnType();  
  8.             Class<?>[] parameterTypes = method.getParameterTypes();  
  9.         }  
  10.   
  11.         //-----------------------------我即將抽取的-------------------------//  
  12.         Field[] declaredFields = clazz.getDeclaredFields();  
  13.         for (Field field : declaredFields) {  
  14.             String name = field.getName();  
  15.             Class c1 = field.getType();  
  16.             String type = c1.getName();  
  17.         }  
  18.         //------------------------------我即將抽取的------------------------//  
  19.     }  
  20.   
  21. }  

選中我即將抽取的代碼,按快捷鍵Ctrl + Alt + M 即可,或者  鼠標右擊 》Refactor 》Extract 》Method 出現如下

抽取后自動生成代碼如下,后續此方法就可以方便的被調用了

  1. public class Demo {  
  2.     private static void getInfo(Object obj) {  
  3.         Class<?> clazz = obj.getClass();  
  4.         Method[] methods = clazz.getMethods();  
  5.         for (Method method : methods) {  
  6.             String name = method.getName();  
  7.             Class<?> returnType = method.getReturnType();  
  8.             Class<?>[] parameterTypes = method.getParameterTypes();  
  9.         }  
  10.   
  11.         //-----------------------------我即將抽取的-------------------------//  
  12.         commonDeal(clazz);  
  13.         //------------------------------我即將抽取的------------------------//  
  14.     }  
  15.   
  16.     private static void commonDeal(Class<?> clazz) {  
  17.         Field[] declaredFields = clazz.getDeclaredFields();  
  18.         for (Field field : declaredFields) {  
  19.             String name = field.getName();  
  20.             Class c1 = field.getType();  
  21.             String type = c1.getName();  
  22.         }  
  23.     }  
  24.   
  25. }  

對應的還有變量的抽取、常量的抽取等,看下圖,這是鼠標右擊 》Refactor 》Extract 操作后出現的效果,里面包含很多的抽取:



免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM