java反射可以獲取一個類中的所有方法,但是這些方法的輸出順序,並非代碼的編寫順序。
我們可以通過自定義一個注解來實現順序輸出類中的方法。
首先,先寫一個類,定義增刪改查4個方法
public class TestMethod { public void add(Object obj) { } public void delete(String a) { } public void update(int b) { } public void find() { } }
然后寫一個測試類看一下輸出順序:
public class Main { public static void main(String[] args) throws ClassNotFoundException { Class<?> clazz = Class.forName("test.TestMethod"); Method[] methods = clazz.getMethods(); for (Method m : methods ) { System.out.println(m.getName()); } } }
輸出結果如下:
add
update
find
delete
wait
wait
wait
equals
toString
hashCode
getClass
notify
notifyAll
可以看到,輸出順序並非代碼的書寫順序,並且還將繼承自Object的方法也打了出來
接下來做這么幾件事情:
1 寫個數組存儲繼承自Object的所有方法,用來過濾
2 自定義注解,用來給方法定義一個順序
3 寫注解的解析器,用來返回這個順序值
4 用Collections寫一個比較器,用來給方法排序
最后遍歷輸出
String[] removeMethods = new String[] { "wait", "equals", "toString", "hashCode", "getClass", "notify", "notifyAll" };
import static java.lang.annotation.ElementType.METHOD; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target({ METHOD }) @Retention(RetentionPolicy.RUNTIME) public @interface MyAnnotation { int value() default 0; }
import java.lang.reflect.Method; public class MyAnnotationProcessor { public int getSequence(Method method) { if (method.isAnnotationPresent(MyAnnotation.class)) { MyAnnotation myAnnotation = (MyAnnotation) method.getAnnotation(MyAnnotation.class); return myAnnotation.value(); } return 0; } }
public class TestMethod { @MyAnnotation(1) public void add(Object obj) { } @MyAnnotation(2) public void delete(String a) { } @MyAnnotation(3) public void update(int b) { } @MyAnnotation(4) public void find() { } }
public class Main {
static String[] removeMethods = new String[] { "wait", "equals", "toString", "hashCode", "getClass",
"notify", "notifyAll" };
public static void main(String[] args) throws ClassNotFoundException { Class<?> clazz = Class.forName("test.TestMethod"); Method[] methods = clazz.getMethods(); List<String> removeList = new ArrayList<>(Arrays.asList(removeMethods)); // 用來存放需要過濾的方法 List<Method> methodList = new ArrayList<>(Arrays.asList(methods)); // 用來存放所有的方法 MyAnnotationProcessor processor = new MyAnnotationProcessor();
Collections.sort(methodList, (m1, m2) -> { // 這個比較的語法依賴於java 1.8 return processor.getSequence(m1) - processor.getSequence(m2); }); for (Method m : methodList) { // 遍歷排序后的方法列表 if (removeList.contains(m.getName())) { continue; } System.out.println(m.getName()); } }
}
最后看一下輸出結果:
add
delete
update
find