註解

refer from :http://www.iteye.com/topic/223891



註解的學習


1.聲明瞭一個註釋 

  1. @Retention(RetentionPolicy.RUNTIME)  
  2. public @interface TestAnno {  
  3.       
  4. }  



2.聲明瞭一個含有private變量a的類 

  1. public class TestAnnotation {  
  2.     @TestAnno  
  3.     private String a;  
  4.   
  5.     public String getA() {  
  6.         return a;  
  7.     }  
  8.   
  9.     public void setA(String a) {  
  10.         this.a = a;  
  11.     }  
  12.   
  13. }  



3.通過反射爲a賦值 

  1. public class MainTest {  
  2.     public static void main(String[] args) throws IllegalArgumentException, IllegalAccessException {  
  3.         TestAnnotation ta=new TestAnnotation();  
  4.         Field[] fs=TestAnnotation.class.getDeclaredFields();  
  5.         for(int i=0;i<fs.length;i++){  
  6.             if(fs[i].isAnnotationPresent(TestAnno.class)){  
  7.                 fs[i].setAccessible(true);  
  8.                 fs[i].set(ta, "你好");  
  9.             }  
  10.         }  
  11.         System.out.println(ta.getA());  
  12.     }  
  13. }  


關鍵是fs[i].setAccessible(true);這個方法,如果不設置這個方法則會拋出java.lang.IllegalAccessException的異常。網上也有人說setAccessible有安全性限制不要隨便亂用。不過至少可以做到

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章