java 反射 顺序_java反射 顺序输出类中的方法

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值