java反射可以获取一个类中的所有方法,但是这些方法的输出顺序,并非代码的编写顺序。
我们可以通过自定义一个注解来实现顺序输出类中的方法。
首先,先写一个类,定义增删改查4个方法
public classTestMethod {public voidadd(Object obj) {
}public voiddelete(String a) {
}public void update(intb) {
}public voidfind() {
}
}
然后写一个测试类看一下输出顺序:
public classMain {public static void main(String[] args) throwsClassNotFoundException {
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 staticjava.lang.annotation.ElementType.METHOD;importjava.lang.annotation.Retention;importjava.lang.annotation.RetentionPolicy;importjava.lang.annotation.Target;
@Target({ METHOD })
@Retention(RetentionPolicy.RUNTIME)public @interfaceMyAnnotation {int value() default 0;
}
importjava.lang.reflect.Method;public classMyAnnotationProcessor {public intgetSequence(Method method) {if (method.isAnnotationPresent(MyAnnotation.class)) {
MyAnnotation myAnnotation= (MyAnnotation) method.getAnnotation(MyAnnotation.class);returnmyAnnotation.value();
}return 0;
}
}
public classTestMethod {
@MyAnnotation(1)public voidadd(Object obj) {
}
@MyAnnotation(2)public voiddelete(String a) {
}
@MyAnnotation(3)public void update(intb) {
}
@MyAnnotation(4)public voidfind() {
}
}
public class Main {
static String[] removeMethods = new String[] { "wait", "equals", "toString", "hashCode", "getClass",
"notify", "notifyAll" };
public static void main(String[] args) throwsClassNotFoundException {
Class> clazz = Class.forName("test.TestMethod");
Method[] methods=clazz.getMethods();
List removeList = new ArrayList<>(Arrays.asList(removeMethods)); // 用来存放需要过滤的方法
List methodList = new ArrayList<>(Arrays.asList(methods)); // 用来存放所有的方法
MyAnnotationProcessor processor= newMyAnnotationProcessor();
Collections.sort(methodList, (m1, m2)->{ // 这个比较的语法依赖于java 1.8return 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