java - How to force instantiation of static fields -
i quite surprised of output of following code:
country class
public class country { private static map<string, country> countries = new hashmap<string, country>(); private final string name; @suppresswarnings("leakingthisinconstructor") protected country(string name) { this.name = name; register(this); } /** country name */ public static country getcountry(string name) { return countries.get(name); } /** register country map */ public static void register(country country) { countries.put(country.name, country); } @override public string tostring() { return name; } /** countries in europe */ public static class europecountry extends country { public static final europecountry spain = new europecountry("spain"); public static final europecountry france = new europecountry("france"); protected europecountry(string name) { super(name); } } }
main method
system.out.println(country.getcountry("spain"));
output
null
is there clean way of forcing class extend country loaded countries map contains country instances?
yes, use static initializer block:
public class country { private static map<string, country> countries = new hashmap<string, country>(); static { countries.put("spain", new eurocountry("spain")); } ...
Comments
Post a Comment