假设下面的类的属性被@Autowired注解
public class MyModel {
private String test;
public String getTest() {
return test;
}
}
下面是spring利用java的反射reflection注入属性
public class Test {
public static void main(String[] args) {
Class<?> clazz = MyModel.class;
MyModel cc = null;
try {
cc = (MyModel) clazz.newInstance();
Field f1 = cc.getClass().getDeclaredField("test");
f1.setAccessible(true);
f1.set(cc, "reflecting on life");
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
System.out.println(cc.getTest());
}
}
或者Apache commons-lang3
//The "true" forces it to set, even with "private".
FieldUtils.writeField(childInstance, "a_field", "Hello", true);