Java通过反射访问注解信息的方法示例
本文实例讲述了Java通过反射访问注解信息的方法。分享给大家供大家参考,具体如下:
一点睛
利用Java的反射机制,可以访问注解信息。比如在调用某个方法时,需要知道该方法的一些基本信息,而这些信息又需要动态获取时,利用发射获取注解信息是一个比较理想的处理方式。
二实战——访问类的某个成员方法的注解信息
1代码
importjava.lang.annotation.Annotation;
importjava.lang.annotation.Documented;
importjava.lang.annotation.ElementType;
importjava.lang.annotation.Retention;
importjava.lang.annotation.RetentionPolicy;
importjava.lang.annotation.Target;
importjava.lang.reflect.Method;
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@interfacetestAnnoation8{
publicStringname()default"methodname";
publicStringunit()default"unit";
}
publicclassch11_8{
publicStringaString;
publicstaticvoidmain(String[]args){
try{
ch11_8ch8=newch11_8();
Methodmethod=ch8.getClass().getMethod("getData1");
Annotationans[]=method.getAnnotations();
for(Annotationannotation:ans){
System.out.println(annotation);
}
Annotationannotation=method.getAnnotation(testAnnoation8.class);
System.out.println(annotation);
}catch(Exceptione){
e.printStackTrace();
}
}
@Deprecated
@testAnnoation8(name="SOC",unit="%")
publicvoidgetData1(){
}
}
2运行
@java.lang.Deprecated()
@testAnnoation8(name=SOC,unit=%)
@testAnnoation8(name=SOC,unit=%)
三实战——访问类的某个成员方法的注解信息
1代码
importjava.lang.annotation.Annotation;
importjava.lang.annotation.Documented;
importjava.lang.annotation.ElementType;
importjava.lang.annotation.Retention;
importjava.lang.annotation.RetentionPolicy;
importjava.lang.annotation.Target;
importjava.lang.reflect.Method;
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@interfacetestAnnoation9{
publicStringname()default"methodname";
publicStringunit()default"unit";
}
publicclassch11_9{
publicStringaString;
publicstaticvoidmain(String[]args){
try{
ch11_9ch9=newch11_9();
Methodmethod=ch9.getClass().getMethod("getData1");
Annotationannotation=method.getAnnotation(testAnnoation9.class);
testAnnoation9t9=(testAnnoation9)annotation;
System.out.println("namevalueis"+t9.name()+";unitis"+t9.unit());
}catch(Exceptione){
e.printStackTrace();
}
}
@Deprecated
@testAnnoation9(name="SOC",unit="%")
publicvoidgetData1(){
}
}
2运行
namevalueisSOC;unitis%
更多java相关内容感兴趣的读者可查看本站专题:《Java面向对象程序设计入门与进阶教程》、《Java数据结构与算法教程》、《Java操作DOM节点技巧总结》、《Java文件与目录操作技巧汇总》和《Java缓存操作技巧汇总》
希望本文所述对大家java程序设计有所帮助。