Java reflection, add volatile modifier to private

2019-09-05 23:19发布

问题:

It's possible to add the volatile modifier to a field that is private and static?

Example Code

// I don't know when test is initalized
public class Test {
    private static String secretString;

    public Test() {
        secretString = "random";
    }
}

public class ReflectionTest extends Thread {
    public void run() {
        Class<?> testClass = Class.forName("Test");
        Field testField = testClass.getDeclaredField("secretString");

        while (testField.get(null) == null) {
            // Sleep, i don't know when test is initalized
            // When it'is i need the String value
            // But this loop never end.
        }
    }
}

I think that if i set the field volatile the loop end without any problem

回答1:

If you don't have access to the class, you cannot modify it.

Instead, find the code that instantiates it, and add a synchronized block around it:

synchronized(Test.class) {
   new Test();
}

Now, in your thread code, do:

while(true) {
   synchronized(Test.class) {
       if(testField.get(null) == null) break;
   }
   // ... whatever 
}

May I ask why you need this? If a field is made private, there is usually a reason for it. You are circumventing the class creator's intent with your use of reflection ... Also, initializing static fields in an instance constructor seems ... fishy :-/