反射7

    xiaoxiao2021-03-25  116

    /** * 在接口中有以下重要的方法: * 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(); } } }

    转载请注明原文地址: https://ju.6miu.com/read-17384.html

    最新回复(0)