Java – why does a program not allow static final variables to be initialized?

I see that the following java code looks good, but it is never compiled:

public class UnwelcomeGuest {

    public static final long GUEST_USER_ID = -1;
    private static final long USER_ID;

    static {
        try {
            USER_ID = getUserIdFromEnvironment();
        } catch (IdUnavailableException e) {
            USER_ID = GUEST_USER_ID;
            System.out.println("Logging in as guest");
        }
    }

    private static long getUserIdFromEnvironment()
            throws IdUnavailableException {
        throw new IdUnavailableException(); // Simulate an error
    }

    public static void main(String[] args) {
        System.out.println("User ID: " + USER_ID);
    }
}//Class ends here


//User defined Exception
class IdUnavailableException extends Exception {

     IdUnavailableException() { }

}//Class ends here

The following is the error message in the IDE: variable user_ ID may have been assigned

Is there a problem with the value assignment of the static final variable?

Solution

The final variable allows at most one assignment in the constructor or initialization block The reason for not compiling is that the Java code analyzer sees two assignments to user in the branch_ ID assignment, these two assignments are not mutually exclusive

The solution to this problem is simple:

static {
    long theId;
    try {
        theId = getUserIdFromEnvironment();
    } catch (IdUnavailableException e) {
        theId = GUEST_USER_ID;
        System.out.println("Logging in as guest");
    }
    USER_ID = theId;
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>