Roland
Roland

Reputation: 7853

Initialization on demand for multiple static variables without static nested classes?

I want to have a class with multiple static variables that will only be initialized on demand.

public class Messages {
    public static final String message1 = init1();
    public static final String message2 = init2();
}

So when somewhere in the code I reference Messages.message1 I want only init1() to be called. If later I access Messages.message2 then only at that time should init2() be called.

I know it is possible to do this with the Initialization-on-demand holder idiom, but this is cumbersome if you have lots of fields.

Is there another way?

Upvotes: 2

Views: 357

Answers (1)

Stanislav Lukyanov
Stanislav Lukyanov

Reputation: 2157

Most common way for lazy initialization is initialization in getter method:

public class Messages {
    private static String message1;
    public static String getMessage1() {
        if (message1 == null)
            message1 = init1();
        return message1;
    }
}

If you want exactly public final static fields then there is no way to achieve separate initialization for them in Java. All class members are initialized together.

Upvotes: 2

Related Questions