在Java枚举常量中实例化昂贵的对象

时间:2018-02-22 18:43:51

标签: java enums

我遇到了一些类似的代码(为了清晰起见而简化)

public enum MyServiceImpl implements MyService {

    A {
        //@Override MyService contract
    },
    B {
        //@Override MyService contract
    },
    C {
        //ExpensiveObject is a complex class which uses DecimalFormat, some regex in the constructor and also ManagementFactory for CPU measurement.
        ExpensiveObject eo = new ExpensiveObject();

        //@Override MyService contract
    };

}

这样做的性能影响是什么?鉴于MyServiceImpl是一个隐含的Singleton,是一次创建ExpensiveObject的成本吗?首次引用MyServiceImpl时是否支付价格?

0 个答案:

没有答案