java - 如何强制实例化静态字段

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

}

主要方法

System.out.println(Country.getCountry("Spain"));

输出

null

是否有任何干净的方法强制加载扩展 Country 的类,以便国家 map 包含所有 Country 实例?

最佳答案

是的,使用 static initializer block :

public class Country {

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

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

    }

...

关于java - 如何强制实例化静态字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5963520/

相关文章:

java - 在 JAX-RS 中使用位置 header 创建响应

java - 在 spring 中创建 bean id 时出错

java - 我是否需要使用 BufferedWriter 和 FileWriter 在将数据写入同一文件时实现同步?

java - 构造函数调用的方法应该是静态的吗?

java - 如何在java中使用数据类,而不使用getter方法?

java - OpenCV Android 无缝克隆错误 : (-215) CV_MAT_TYPE(mtype) == m. type()

java - 如何让我的程序根据特定情况重复执行?

static - 使用 PowerMock 通过 @InjectMocks 模拟静态属性

c++ - 从派生类访问静态常量变量

c++ - 如何防止静态类成员变量需要两个定义/声明?