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

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 出现如下

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

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 操作后出现的效果,里面包含很多的抽取:

内容来源于网络如有侵权请私信删除

文章来源: 博客园

原文链接: https://www.cnblogs.com/eternityz/p/12239742.html

你还没有登录,请先登录注册
  • 还没有人评论,欢迎说说您的想法!

相关课程