The final field may not/already have been initialized [duplicate]

﹥>﹥吖頭↗ 提交于 2019-12-10 12:53:43

问题


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 not have 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 already have been assigned:

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?


回答1:


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!
}



回答2:


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;
    }
}



回答3:


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.

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

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.



来源:https://stackoverflow.com/questions/14599721/the-final-field-may-not-already-have-been-initialized

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