Annotation(自定义注解)反射获取注解
2016-01-15 20:50
288 查看
package com.ygl.annotion;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
String hello() default "ygl";
String world();
}
//*************************************
package com.ygl.annotion;
@MyAnnotation(hello="beijing",world="shanghai")
public class MyTest {
@MyAnnotation(hello="tianjin",world="shanghai")
@Deprecated
@SuppressWarnings("unchecked")
public void output(){
System.out.println("output something");
}
}
//*************************************
package com.ygl.annotion;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
public class MyReflection {
public static void main(String[] args) throws Exception {
MyTest myTest=new MyTest();
Class<MyTest> c=MyTest.class;
try {
Method method=c.getDeclaredMethod("output", new Class[]{});
if(method.isAnnotationPresent(MyAnnotation.class)){//判定方法上是否被注解修饰
method.invoke(myTest, new Object[]{});//存在则调用方法
MyAnnotation myannotation=method.getAnnotation(MyAnnotation.class);
String hello=myannotation.hello();
String world=myannotation.world();
System.out.println(hello+world);
Annotation[] annotations=method.getAnnotations();
/*@MyAnnotation(hello="tianjin",world="shanghai")
@Deprecated
@SuppressWarnings("unchecked")-->source
public void output(){
System.out.println("output something");
}*/
for(Annotation annotation:annotations){
System.out.println(annotation.annotationType().getName());
//输出//com.ygl.annotion.MyAnnotation --》RUNTIME
//java.lang.Deprecated --》RUNTIME
}
}
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
相关文章推荐
- HDU 1713 相遇周期【这也算数学吗?】
- hadoop数据节点通信异常【启动hadoop集群遇到错误org.apache.hadoop.ipc.Client: Retrying connect to server】
- 【Codeforces 570D 】Tree Requests dfs序+二分
- Python中函数的参数传递方式
- GOOGLE PROTOBUF开发者指南
- Ant Counting(DP)
- Struts中ActionContext和ServletActionContext的比较
- 蓝桥杯-基础练习-十六进制转八进制
- HRBUST 1621 迷宫问题II
- C++:重载函数1(和与连接)
- 01背包
- 深入分析JavaWeb Item54 -- Spring中的AOP面向切面编程2
- 编程策略类note
- hbase异常:java.io.IOException: Unable to determine ZooKeeper ensemble
- 如何自己创建Servlet并配置web.xml
- 史上最全最经常使用的正則表達式-(基本够用值得收藏)
- Mysql Windows 发布多个实例
- Homework1-15
- 蓝桥杯-基础练习-十进制转十六进制
- 题目1019:简单计算器