反射+annotation模拟spring2.5的@Autowired标签访问private变量
这段时间用了一下spring 2.5的@Autowired注释来做依赖注入,感觉真的不错,省掉了get、set的方法,整个类也看起来更加舒服了。
在这期间对于@Autowired注释访问private的变量一直感到很好奇,查了一下相关资料,写了一个小例子。不过没看过@Autowired的源码,不确定是不是这样做的,应该差不多吧。
代码如下:
1.声明了一个注释
@Retention(RetentionPolicy.RUNTIME)public @interface TestAnno {}public class TestAnnotation {@TestAnnoprivate String a;public String getA() {return a;}public void setA(String a) {this.a = 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());}}
1 楼 jakoes 2009-07-24 最好赋一下源码