反射7
来源:互联网 发布:歌德巴赫猜想c语言 编辑:程序博客网 时间:2024/05/16 14:59
/** * 在接口中有以下重要的方法: * 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
- 反射7
- 7 java反射总结
- [7-03]反射小结
- 反射
- 反射
- 反射
- 反射
- 反射
- 反射
- 反射
- 反射
- 反射
- 反射
- 反射
- 反射
- 反射
- 反射
- 反射
- 位域复习
- 题目1001:A+B for Matrices
- 小写字母到大写字母的转换
- android网络请求问题:android.os.NetworkOnMainThreadException
- 廖雪峰python教程阅读之数据类型和变量
- 反射7
- CSS居中小技巧
- PAT 乙级全部源码(已更新完http://blog.csdn.net/caicaiatnbu)
- CentOS下命令行实现普通用户和root用户切换
- hive:For direct MetaStore DB connections, we don't support retries at the client level
- 漫步数理统计五——条件概率与独立(上)
- 百度地图:230错误 APP Scode校验失败问题解决办法
- HTTP头信息
- 指令总计-1