The final field may not/already have been initialized

15,935

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

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

Solution 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.

Share:
15,935
sp00m
Author by

sp00m

Updated on June 04, 2022

Comments

  • sp00m
    sp00m about 2 years

    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?

  • sp00m
    sp00m over 11 years
    Interesting solution, many thanks!
  • sp00m
    sp00m over 11 years
    That suits perfectly my needs, many thanks!