In Java, the reflection of an enum object is created

Source: Internet
Author: User

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 ();
}

}

}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.