java Singleton - prevent multiple creation through reflection

前端 未结 6 898
无人及你
无人及你 2021-01-30 22:52

I have a singleton like this.

public class BookingFactory {

    private final static BookingFactory instance;

    static {
        instance = new BookingFactor         


        
6条回答
  •  -上瘾入骨i
    2021-01-30 23:40

    Try using an enum. enums make for good Singletons.

    public static enum BookingFactory {
        INSTANCE;
        public static BookingFactory getInstance() {
            return INSTANCE;
        }
    }
    

    You can't create an enum via reflection.

    The getInstance() method is superfluous but makes it easier to run your test, throwing the following exception:

    java.lang.IllegalArgumentException: Cannot reflectively create enum objects
        at java.lang.reflect.Constructor.newInstance(Constructor.java:530)
        at MultiSingletonTest.main(MultiSingletonTest.java:40)
    

    Oh look, someone already gave the enum answer. Posting anyway for more completeness.

提交回复
热议问题