How to instantiate a Singleton multiple times?

后端 未结 9 1883
醉酒成梦
醉酒成梦 2020-12-19 04:08

I need a singleton in my code. I implemented it in Java and it works well. The reason I did it, is to ensure that in a mulitple environment, there is only one instance of th

9条回答
  •  无人及你
    2020-12-19 04:42

    You can invoke the private constructor of your singleton class using reflection to create a new instance of the class.

    class MySingleton {
        private MySingleton() {
        }
    }
    
    class Test {
        public void test() throws Exception {
            Constructor constructor = MySingleton.class.getConstructor();
            constructor.setAccessible(true);
            MySingleton otherSingleton = constructor.newInstance();
        }
    }
    

提交回复
热议问题