1

today,i learned that we could use spring's @AutoWired annotation to complete auto-injection, @AutoWired could be used in many conditions ,like

@AutoWired
public void setInstrument(Instrument instrument){
  this.instrument = instrument;
}

but we can also put the @AutoWired on a private field,like this

@AutoWired
private Instrument instrument;

i was wondering ,how could spring inject an object into a private field,i know we could use reflection of java to get some meta data,when i use reflection to set a object on a private field ,here comes a problem ,following is the stacktrace

 java.lang.IllegalAccessException: Class com.wire.with.annotation.Main can not access a member of class com.wire.with.annotation.Performer with modifiers "private"

some body can explain it ? why spring could inject an object into a private field with no setter method . thanks a lot

4

2 回答 2

7

这是使用反射完成的,您需要Filed.setAccessible(true)访问这些private字段。

privateField.setAccessible(true);//works ,if java security manager is disable

更新:-

例如-

public class MainClass {
    private String string="Abcd";

    public static void main(String... arr) throws SecurityException, IllegalArgumentException, IllegalAccessException, InvocationTargetException, NoSuchFieldException{
        MainClass mainClass=new MainClass();
        Field stringField=MainClass.class.getDeclaredField("string");
        stringField.setAccessible(true);//making field accessible 
        /*if SecurityManager enable then,  
        java.security.AccessControlException: access denied will be thrown here*/
        stringField.set(mainClass, "Defgh");//seting value to field as it's now accessible
        System.out.println("value of string ="+stringField.get(mainClass));//getting value from field then printing it on console
    }
}

Java 安全管理器(如果启用)还阻止 Spring 访问私有字段

于 2013-07-16T12:44:11.280 回答
3

我猜您忘记设置setAccessible(true)您要访问的字段:

public class Main {

    private String foo;

    public static void main(String[] args) throws Exception {
        // the Main instance
        Main instance = new Main();
        // setting the field via reflection
        Field field = Main.class.getDeclaredField("foo");
        field.setAccessible(true);
        field.set(instance, "bar");
        // printing the field the "classic" way
        System.out.println(instance.foo); // prints "bar"
    }

}

请也阅读此相关帖子

于 2013-07-16T12:44:55.033 回答