反射7

/**
     * 在接口中有以下重要的方法:
     * getAnnotations(Class annotationType) 获取一个指定的annotation类型
     * getAnnotations() 获取所有的Annotation
     * getDeclaredAnnotations()  获取声明过的所有Annotation
     * isAnnotationPresent(Class<? extends Annotation> annotationClass) 这个annotation是否出现
     */

    @SuppressWarnings("unchecked")  //java自带的注解Retention的policy为SOURCE,该注解的意思是这个方法中的警告将被忽略
    @Deprecated//java自带的注解Retention的policy为RUNTIME
    @RetentionTest(hello = "Dean", world = "25")    //自定义的注解Retention的policy为RUNTIME
    @RetentionTest.RetentionTest1(hello = "aaaaaaa")//自定义的注解Retention的policy为CLASS
    public void TestMethod() {
        System.out.println("this is a method");
    }

}

public class MainTest {

    public void mainTest() {
        Test testa = new Test();
        //通过反射得到TestMethod方法
        Class<Test> cla = Test.class;
        try {
            //找到test类中的TestMethod方法
            Method method = cla.getMethod("TestMethod");
            //AnnotatedElement接口中的方法isAnnotationPresent(),判断传入的注解类型是否存在
            if (method.isAnnotationPresent(RetentionTest.class)) {
                method.invoke(testa, new Object[]{});
                //AnnotatedElement接口中的方法getAnnotation(),获取传入注解类型的注解
                RetentionTest retentionTest = method.getAnnotation(RetentionTest.class);
                //拿到注解中的属性
                String hello = retentionTest.hello();
                String world = retentionTest.world();
                Log.i("test", "name:" + hello + "   age:" + world);
            }
            //因为RetentionTest1的枚举定义为CLASS,所以它是不会在虚拟机中运行的
            if (method.isAnnotationPresent(RetentionTest.RetentionTest1.class)) {
                method.invoke(testa);
                //AnnotatedElement接口中的方法getAnnotation(),获取传入注解类型的注解
                RetentionTest.RetentionTest1 retentionTest = method.getAnnotation(RetentionTest.RetentionTest1.class);
                //拿到注解中的属性
                String hello = retentionTest.hello();
                Log.i("test", "nameaaaaa:" + hello );
            }
            //AnnotatedElement接口中的方法getAnnotations(),获取所有注解
            Annotation[] annotations = method.getAnnotations();
            //循环注解数组打印出注解类型的名字
            for (Annotation annotation : annotations) {
                Log.i("test", annotation.annotationType().getName());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}





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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值