Intellij Idea使用教程彙總篇html
問題:有時候一個方法裏面嵌套了不少邏輯,想拆分爲多個方法方便調用;或者一個方法複用性很高,這時,這個方法嵌套在局部方法裏面確定是不方便的,如何快速抽取出這個方法?java
- 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();
- }
-
- }
-
- }
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 出現以下
app
抽取後自動生成代碼以下,後續此方法就能夠方便的被調用了oop
- 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();
- }
- }
-
- }
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 操做後出現的效果,裏面包含不少的抽取:this