给私有静态字段添加volatile修饰符

给私有静态字段添加volatile修饰符

本文介绍了Java反射,给私有静态字段添加volatile修饰符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以将 volatile 修饰符添加到私有和静态字段?

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

示例代码

// 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.
        }
    }
}

我认为如果我将字段设置为 volatile 循环结束没有任何问题

I think that if i set the field volatile the loop endwithout 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:

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

这篇关于Java反射,给私有静态字段添加volatile修饰符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 08:09