只知道如何用Autowired注解,知道可以替代set,get方法,很方便,卻一直不知道,為什么可以代替
今天探索一下原因,所謂知其然還要知其所以然,才能理解的更好,記憶的更牢,才能轉化為自己的知識。
這都是利用了java的注解原理:
如下:
1.先定義一個注解
1 /** 2 * @author jing.ming 3 * @version 創建時間:2015年11月3日 上午9:35:03 4 * 聲明一個注解 5 */ 6 @Retention(RetentionPolicy.RUNTIME) 7 public @interface TestAnno { 8 9 }
2.定義一個類
1 /** 2 * @author jing.ming 3 * @version 創建時間:2015年11月3日 上午9:37:34 4 * 程序的簡單說明 5 */ 6 public class TestAnnotation { 7 8 @TestAnno 9 private String a ; 10 11 public String getA(){ 12 return a ; 13 } 14 public void setA(String a){ 15 this.a = a ; 16 } 17 }
3.通過反射為上面的類賦值
1 /** 2 * @author jing.ming 3 * @version 創建時間:2015年11月3日 上午9:39:47 4 * 通過反射為a賦值 5 */ 6 public class MainReflectTest { 7 8 public static void main(String[] args) { 9 TestAnnotation ta = new TestAnnotation() ; 10 Field[] fs = TestAnnotation.class.getDeclaredFields(); 11 for(int i=0;i<fs.length;i++){ 12 if(fs[i].isAnnotationPresent(TestAnno.class)){ 13 fs[i].setAccessible(true); 14 try { 15 fs[i].set(ta, "Hello World"); 16 } catch (IllegalArgumentException e) { 17 e.printStackTrace(); 18 } catch (IllegalAccessException e) { 19 e.printStackTrace(); 20 } 21 } 22 } 23 24 System.out.println(ta.getA()); 25 } 26 27 }
關鍵是fs[i].setAccessible(true);這個方法,如果不設置這個方法則會拋出java.lang.IllegalAccessException的異常。網上也有人說setAccessible有安全性限制不要隨便亂用。不過至少可以做到.
這里有一個詳細的講解:
http://swiftlet.net/archives/734