views:

25

answers:

1

I wonder if it's reliable to use a construction like:

private static final Map<String, String> engMessages;
private static final Map<String, String> rusMessages;

static {
    engMessages = new HashMap<String, String> () {{
        put ("msgname", "value");
    }};
    rusMessages = new HashMap<String, String> () {{
        put ("msgname", "значение");
    }};
}

private static Map<String, String> msgSource;

static {
    msgSource = engMessages;
}

public static String msg (String msgName) {
    return msgSource.get (msgName);
}

Is there a possibility that I'll get NullPointerException because msgSource initialization block will be executed before the block which initializes engMessages?

(about why don't I do msgSource initialization at the end of upper init. block: just the matter of taste; I'll do so if the described construction is unreliable)

+1  A: 

Yes, static initializer blocks are guaranteed to execute in textual order.

From the JLS, section 8.7:

The static initializers and class variable initializers are executed in textual order.

Use of class variables whose declarations appear textually after the use is sometimes restricted, even though these class variables are in scope. See §8.3.2.3 for the precise rules governing forward reference to class variables.

Personally though, I'd put all the variable declarations at the start, and then a single static initializer block. I consider that to be a lot easier to follow.

Jon Skeet
Thanks for the fast answer!
Roman