Enumeration enum with reflection

The enumeration itself is a Class class

Be aware that reflection cannot destroy enum singletons , but now we can try

public enum EnumSingle{
    INSTANCE;
    public EnumSingle getInstance(){
        return INSTANCE;
    }
}


public class Test{
    public static void main(String[] args) throws NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
    	EnumSingle instance1 = EnumSingle.INSTANCE;
        //这里需要注意的是不要写成Integer.class,这里的int.class是确定的
    	Constructor<EnumSingle> declaredConstructor = EnumSingle.class.getDeclaredConstructor(String.class,int.class);
    	//破除私有权限
    	declaredConstructor.setAccessible(true);
    	EnumSingle instance2 = declaredConstructor.newInstance();
    	System.out.println(instance1);
    	System.out.println(instance2);
    }
}

The exception thrown like this is

You will find that reflection does not create singletons of enums.

Note that there is no parameterless construction in the enumeration, but two parameters (String, int)

Guess you like

Origin blog.csdn.net/qq_44709970/article/details/124373887