問題:有時候一個方法里面嵌套了很多邏輯,想拆分為多個方法方便調用;或者一個方法復用性很高,這時,這個方法嵌套在局部方法里面肯定是不方便的,如何快速抽取出這個方法?
- 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 操作后出現的效果,里面包含很多的抽取: