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