为什么反射不能通过以下代码打破私有构造函数来破坏单例模式。 InstanctTwo上应该有一个新实例,但没有。
Constructor[] constructors = EagerInitializedSingleton.class.getDeclaredConstructors();
for (Constructor constructor : constructors) {
//Below code will destroy the singleton pattern
constructor.setAccessible(true);
instanceTwo = (EagerInitializedSingleton) constructor.newInstance();
break;
}
答案 0 :(得分:1)
如果EagerInitializedSingleton
是枚举,它就不起作用。 (我不评论它是否适用于其他情况)
class Ideone
{
enum EagerInitializedSingleton { INSTANCE }
public static void main (String[] args) throws java.lang.Exception
{
Constructor[] constructors = EagerInitializedSingleton.class.getDeclaredConstructors();
for (Constructor constructor : constructors) {
//Below code will destroy the singleton pattern
constructor.setAccessible(true);
System.out.println((EagerInitializedSingleton) constructor.newInstance());
}
}
}
Exception in thread "main" java.lang.IllegalArgumentException: Cannot reflectively create enum objects at java.lang.reflect.Constructor.newInstance(Constructor.java:416) at Ideone.main(Main.java:19)