Java reflection, add volatile modifier to private static field

不羁岁月 提交于 2019-12-13 03:17:54

问题


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 :-/



来源:https://stackoverflow.com/questions/27565619/java-reflection-add-volatile-modifier-to-private-static-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!