Java通過反射訪問注解信息的方法示例
本文實例講述了Java通過反射訪問注解信息的方法。分享給大家供大家參考,具體如下:
一 點睛
利用Java的反射機制,可以訪問注解信息。比如在調(diào)用某個方法時,需要知道該方法的一些基本信息,而這些信息又需要動態(tài)獲取時,利用發(fā)射獲取注解信息是一個比較理想的處理方式。
二 實戰(zhàn)——訪問類的某個成員方法的注解信息
1 代碼
import java.lang.annotation.Annotation; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.reflect.Method; @Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) @interface testAnnoation8 { public String name() default "methodname"; public String unit() default "unit"; } public class ch11_8 { public String aString; public static void main( String[] args ) { try { ch11_8 ch8 = new ch11_8(); Method method = ch8.getClass().getMethod("getData1"); Annotation ans[] = method.getAnnotations(); for (Annotation annotation : ans) { System.out.println(annotation); } Annotation annotation = method.getAnnotation(testAnnoation8.class); System.out.println(annotation); } catch (Exception e) { e.printStackTrace(); } } @Deprecated @testAnnoation8(name = "SOC", unit = "%") public void getData1() { } }
2 運行
@java.lang.Deprecated()
@testAnnoation8(name=SOC, unit=%)
@testAnnoation8(name=SOC, unit=%)
三 實戰(zhàn)——訪問類的某個成員方法的注解信息
1 代碼
import java.lang.annotation.Annotation; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.reflect.Method; @Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) @interface testAnnoation9{ public String name() default "methodname"; public String unit() default "unit"; } public class ch11_9 { public String aString; public static void main(String[] args) { try { ch11_9 ch9=new ch11_9(); Method method=ch9.getClass().getMethod("getData1"); Annotation annotation=method.getAnnotation(testAnnoation9.class); testAnnoation9 t9=(testAnnoation9)annotation; System.out.println("name value is "+t9.name()+"; unit is "+t9.unit()); } catch (Exception e) { e.printStackTrace(); } } @Deprecated @testAnnoation9(name = "SOC", unit = "%") public void getData1(){ } }
2 運行
name value is SOC; unit is %
更多java相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Java面向?qū)ο蟪绦蛟O(shè)計入門與進階教程》、《Java數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Java操作DOM節(jié)點技巧總結(jié)》、《Java文件與目錄操作技巧匯總》和《Java緩存操作技巧匯總》
希望本文所述對大家java程序設(shè)計有所幫助。
相關(guān)文章
解析Java的JNI編程中的對象引用與內(nèi)存泄漏問題
這篇文章主要介紹了Java的JNI編程中的對象引用與內(nèi)存泄漏問題,重點講述了局部和全局引用時一些值得注意的地方,需要的朋友可以參考下2015-11-11java中Memcached的使用實例(包括與Spring整合)
這篇文章主要介紹了java中Memcached的使用實例(包括與Spring整合),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-07-07