如何强制实例化静态字段

eli*_*ocs 7 java static

我对以下代码的输出感到非常惊讶:

国家级

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);
    }

    /** Get country by name */
    public static Country getCountry(String name) {
        return countries.get(name);
    }

    /** Register country into 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);
        }
    }

}
Run Code Online (Sandbox Code Playgroud)

主要方法

System.out.println(Country.getCountry("Spain"));
Run Code Online (Sandbox Code Playgroud)

产量

空值

是否有任何干净的方法强制扩展国家/地区的类,以便国家地图包含所有国家/地区实例?

Pet*_*ego 7

是的,使用静态初始化程序块:

public class Country {

    private static Map<String, Country> countries = new HashMap<String, Country>();

    static {
        countries.put("Spain", new EuroCountry("Spain"));

    }

...
Run Code Online (Sandbox Code Playgroud)