问题:有时候一个方法里面嵌套了很多逻辑,想拆分为多个方法方便调用;或者一个方法复用性很高,这时,这个方法嵌套在局部方法里面肯定是不方便的,如何快速抽取出这个方法?

public class Demo {  
    private static void getInfo(Object obj) {  
        Class<?> clazz = obj.getClass();  
        Method[] methods = clazz.getMethods();  
        for (Method method : methods) {  
            String name = method.getName();  
            Class<?> returnType = method.getReturnType();  
            Class<?>[] parameterTypes = method.getParameterTypes();  
        }  
  
        //-----------------------------我即将抽取的-------------------------//  
        Field[] declaredFields = clazz.getDeclaredFields();  
        for (Field field : declaredFields) {  
            String name = field.getName();  
            Class c1 = field.getType();  
            String type = c1.getName();  
        }  
        //------------------------------我即将抽取的------------------------//  
    }  
  
}  

选中我即将抽取的代码,按快捷键Ctrl + Alt + M 即可,或者 鼠标右击 》Refactor 》Extract 》Method 出现如下

idea抽取方法

抽取后自动生成代码如下,后续此方法就可以方便的被调用了

public class Demo {  
    private static void getInfo(Object obj) {  
        Class<?> clazz = obj.getClass();  
        Method[] methods = clazz.getMethods();  
        for (Method method : methods) {  
            String name = method.getName();  
            Class<?> returnType = method.getReturnType();  
            Class<?>[] parameterTypes = method.getParameterTypes();  
        }  
  
        //-----------------------------我即将抽取的-------------------------//  
        commonDeal(clazz);  
        //------------------------------我即将抽取的------------------------//  
    }  
  
    private static void commonDeal(Class<?> clazz) {  
        Field[] declaredFields = clazz.getDeclaredFields();  
        for (Field field : declaredFields) {  
            String name = field.getName();  
            Class c1 = field.getType();  
            String type = c1.getName();  
        }  
    }  
  
}  

对应的还有变量的抽取、常量的抽取等,看下图,这是鼠标右击 》Refactor 》Extract 操作后出现的效果,里面包含很多的抽取:
idea抽取方法

相关文章:

  • 2021-12-02
  • 2021-08-19
  • 2021-06-18
  • 2022-12-23
  • 2022-12-23
  • 2021-04-12
  • 2021-05-31
  • 2022-12-23
猜你喜欢
  • 2021-07-20
  • 2022-01-08
  • 2021-04-09
  • 2022-12-23
  • 2021-10-10
相关资源
相似解决方案