refer from :http://www.iteye.com/topic/223891
註解的學習
1.聲明瞭一個註釋
- @Retention(RetentionPolicy.RUNTIME)
- public @interface TestAnno {
- }
2.聲明瞭一個含有private變量a的類
- public class TestAnnotation {
- @TestAnno
- private String a;
- public String getA() {
- return a;
- }
- public void setA(String a) {
- this.a = a;
- }
- }
3.通過反射爲a賦值
- public class MainTest {
- public static void main(String[] args) throws IllegalArgumentException, IllegalAccessException {
- TestAnnotation ta=new TestAnnotation();
- Field[] fs=TestAnnotation.class.getDeclaredFields();
- for(int i=0;i<fs.length;i++){
- if(fs[i].isAnnotationPresent(TestAnno.class)){
- fs[i].setAccessible(true);
- fs[i].set(ta, "你好");
- }
- }
- System.out.println(ta.getA());
- }
- }
關鍵是fs[i].setAccessible(true);這個方法,如果不設置這個方法則會拋出java.lang.IllegalAccessException的異常。網上也有人說setAccessible有安全性限制不要隨便亂用。不過至少可以做到