2

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?

Roland
  • 7,525
  • 13
  • 61
  • 124

1 Answers1

2

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.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
Stanislav Lukyanov
  • 2,147
  • 10
  • 20