The Java enum is singleton class (only one instance). Java uses compilers and JVMs to prevent an enum from generating more than one class: You cannot use the new, Clone (), De-serialization, and Reflection APIs to produce an enum's instance.
So there are other ways to create an enumerated object by reflection:
For example: Public enum Color ... {
Red,blue,green,black,white;
}
If you use Class.newinstance () to create, the runtime will definitely report an exception.
But Java also gives us an enum class that can directly generate an object for an enum. This is mainly used in the way it provides: Enum.valueof (Class,value);
Examples are as follows: Public enum Color ... {
Red,blue,green,black,white;
}
public class Refcolor ... {
public color color;
}
public class Testenum ... {
public static void Main (string[] args) ... {
Try ... {
Refcolor obj=new Refcolor ();
Class clazz=class.forname ("Color");
Field Field=obj.getclass (). Getdeclaredfield ("color");
Field.set (obj, enum.valueof (Clazz, "Red"));
System.out.println (Obj.color);
catch (Exception e) ... {
E.printstacktrace ();
}
}
}