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
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:
Now, in your thread code, do:
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 :-/