java 最后一个字段可能没有/已经被初始化

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14599721/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 16:47:23  来源:igfitidea点击:

The final field may not/already have been initialized

javainitializationfieldfinal

提问by sp00m

Possible Duplicate:
How to handle a static final field initializer that throws checked exception

可能的重复:
如何处理抛出已检查异常的静态最终字段初始值设定项

In this example, I get the error The blank final field myClass may nothave been initialized:

在此示例中,我收到错误The blank final field myClass may nothave been initialized

private final static MyClass myClass; // <-- error

static {
    try {
        myClass = new MyClass(); // <-- throws exception
        myClass.init();
    } catch (Exception e) {
        // log
    }
}

In that example, I get the error The final field myClass may alreadyhave been assigned:

在这个例子中,我得到了错误的最后一个字段myClass的可能已经被分配

private final static MyClass myClass;

static {
    try {
        myClass = new MyClass(); // <-- throws exception
        myClass.init();
    } catch (Exception e) {
        myClass = null; // <-- error
        // log
    }
}

In there any solution to that issue?

那个问题有什么解决办法吗?

回答by kutschkem

private final static MyClass myClass;

static {
    MyClass my;
    try {
        my = new MyClass();
        my.init();
    } catch (Exception e) {
        my = null;
        // log
    }
    myClass = my; //only one assignment!
}

回答by Denys Séguret

Here's a solution :

这是一个解决方案:

private final static MyClass myClass = buildInstance();

private static MyClass buildInstance() {
    try {
        MyClass myClass = new MyClass();
        myClass.init();
        return myClass;
    } catch (Exception e) {
        return null;
    }
}

回答by jbx

If your class is final it can't change values once it is initialised. What you are doing in the second snippet is that you are first assigning it to new MyClass()and then if an Exception is thrown in init()you then change it to null.

如果您的课程是最终课程,则一旦初始化就无法更改值。您在第二个代码段中所做的是首先将其分配给new MyClass(),然后如果抛出异常,init()则将其更改为null.

This is not allowed. If new MyClass()does not throw an Exception why don't you put it at the top line?

这是不允许的。如果new MyClass()没有抛出异常,为什么不把它放在最上面?

Warning though, that if init()throws an Exception, you will still have an unintialised instance of MyClass. It doesn't seem that the way you're working with this class matches the way its designed to work.

但是警告,如果init()抛出异常,您仍然会有一个未初始化的MyClass. 您使用此类的方式似乎与其设计的工作方式不匹配。