简体   繁体   English

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

[英]how to initialize static final variable from other class in java

I want to initialize Final.value in Main method.我想在 Main 方法中初始化 Final.value。 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;


}

You cannot.你不能。 Your perception might be that main happens before everything else, so it is safe to initialise things there, but that is incorrect.您的看法可能是main发生在其他一切之前,因此在那里初始化事物是安全的,但这是不正确的。

Consider the following code.考虑以下代码。

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

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

class Foo
{
    static int i;
}

It does not print 100. It prints 0 because there are other things which happen before main .它不打印 100。它打印 0 因为在main之前发生了其他事情。

Making the field final does not change that fact.将字段设为 final 并不会改变这一事实。


You have two options for static initialization.您有两种静态初始化选项。 In a static initializer block, like you showed, or in-line:在静态初始化程序块中,如您所示,或内嵌:

static final int value = 421

Java prevents you from doing what you want to do for a good reason: because it is likely to lead to bugs. Java 阻止您做您想做的事情是有充分理由的:因为它可能会导致错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在java中的子类(子类)中初始化静态最终变量 - initialize static final variable in child class(sub class) in java 如何在静态类中初始化最终的静态变量? - How can I initialize final static variable in a static class? 是否可以从Java中的配置文件初始化静态最终变量? - Is it possible to initialize a static final variable from a configuration file in Java? 初始化静态最终变量 - Initialize static final variable 如何在Java中抽象父级的子类中初始化受保护的最终变量? - How to initialize a protected final variable in a child class of an abstract parent in Java? Java,静态变量不会从类外部进行初始化 - Java, static variable doesn't initialize from outside of class 导入的java类中的public static final变量 - public static final variable in an imported java class 修改最终公共类Java中的最终静态变量 - Modifying final static variable within final public class Java 如何从Java中的子代为最终的静态变量赋值? - How to assign a value to a final static variable from a child inside java? 如何使用REFLECTION或任何其他API在最终类中初始化私有变量? - How to initialize a private variable in a final class using REFLECTION or any other API?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM