java - 如何从Java中的其他类初始化静态最终变量

标签 java class static constants final

I want to initialize Final.value in Main method. Is it possible to initialize static final constant in other class than in its deceleration class?

public class Main {

    public static void main(String[] args) {
        //I want to initialize Final.value in Main method.
    }

}

class Final {
    //here is the static final variable which can be assigned vai a static block
    //but how do I initialize it in the main method if I don't use the static block?
    static final int value;


}

最佳答案

你不能。您可能认为 main 发生在其他所有事情之前,因此在那里初始化事物是安全的,但这是不正确的。

考虑以下代码。

class Scratch
{
    static
    {
        System.out.println(Foo.i);    
    }

    public static void main(String[] args)
    {
        Foo.i = 100;
    }
}

class Foo
{
    static int i;
}

它不会打印 100。它会打印 0,因为在 main 之前还发生了其他事情。

使该字段成为最终字段并不会改变这一事实。

<小时/>

静态初始化有两种选择。在静态初始化 block 中,如您所示,或内联:

static final int value = 421

Java 阻止你做你想做的事情是有充分理由的:因为它可能会导致错误。

关于java - 如何从Java中的其他类初始化静态最终变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59776216/

相关文章:

java - Android Studio 中 ssl 认证的 url 抛出 IOException

class - 类名中的 "Helper"这个词是代码异味吗?

java - 使用 Java 反射更改私有(private)静态最终字段

java - 如何增加与数据库交互的类的测试覆盖率?

java - 什么会导致 Sun 的 JavaKeyStore.engineStore() 方法中出现 NullPointerException?

c++ - "Typedef declaration"和 "Class declaration"之间的区别

java - 当使用 ClassName.staticMethod() 时,编译器、静态方法或实例方法首先查找哪个方法?

dynamic - 从静态语言转向动态语言

java - 如何删除JAVA字符串中的 "all new line character"

c# - 不能在不同的命名空间中使用我的新字段