如下是示例代码
package demo.pattern.singleton;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
public class EnumStarvingSingleton {
private EnumStarvingSingleton(){}
public static EnumStarvingSingleton getInstance(){
return ContainerHolder.HOLDER.instance;
}
private enum ContainerHolder{
HOLDER;
private EnumStarvingSingleton instance;
ContainerHolder(){
instance = new EnumStarvingSingleton();
}
}
public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
Class<ContainerHolder> clazz = ContainerHolder.class;
Constructor<ContainerHolder> constructor = clazz.getDeclaredConstructor();
constructor.setAccessible(true);
ContainerHolder newInstance = constructor.newInstance();
}
}
我的问题是:
ContainerHolder枚举类不是有一个无参的构造函数吗?
ContainerHolder(){
instance = new EnumStarvingSingleton();
}
那为什么下面这行代码获取不到对应的构造函数呢?
Constructor<ContainerHolder> constructor = clazz.getDeclaredConstructor();