Java singleton - null静态变量(无法解释)

时间:2014-06-18 10:25:27

标签: java static singleton

有人可以解释一下如何可能,该方法获取(..)为输入ConfiguratorType.SKODA抛出IllegalStateException(变量配置器包含{SKODA = null}) ?它怎么可能为null,我不明白为什么SkodaConfigurator.INSTANCE返回null。它应该永远不会为空或我错了?代码在servlet环境Java 7中执行。

谢谢

public class CarConfigurators {

    private static Map<ConfiguratorType, CarConfigurator> configurators
          = new EnumMap<ConfiguratorType, CarConfigurator>(ConfiguratorType.class);

    static {
        configurators.put(ConfiguratorType.SKODA, SkodaConfigurator.INSTANCE);
        // ..
    }

    public static CarConfigurator obtain(ConfiguratorType type) {
        CarConfigurator configurator = configurators.get(type);
        if (configurator == null)
            throw new IllegalStateException("Car configurator of type " + type + " is not registered.");
        return configurator;
    }
   ...
}


public class SkodaConfigurator extends CarConfigurator {

     public static final SkodaConfigurator INSTANCE = new SkodaConfigurator();
     ...
}

public enum ConfiguratorType {
    SKODA,
    // ..
}

2 个答案:

答案 0 :(得分:1)

静态代码不能同时全部运行,静态初始化的各个部分必须以给定的顺序发生。显然,在这种情况下,执行configurations.put(...)的静态块在初始化SkodaConfiguration中的静态变量之前运行。

答案 1 :(得分:0)

这与静态初始化顺序有关。 我从另一个答案中找到了这个

public class Main {

    {
        System.out.printf("NON-STATIC BLOCK\n");
    }

    static{
        System.out.printf("STATIC BLOCK\n");
    }

    public static Main m = new Main();

    public Main(){
        System.out.printf("MAIN CONSTRUCTOR\n");
    }

    public static void main(String... args) {
        //Main m = new Main();
        System.out.printf("MAIN METHOD\n");

    }
}

输出:

STATIC BLOCK

NON-STATIC BLOCK

MAIN CONSTRUCTOR

MAIN METHOD

请仔细阅读:Java Static Initialization Order