}
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(); } } }
