Java enum class syntax and usage parsing

Source: Internet
Author: User
Tags throwable

I. Grammar
1. Enum is all called enumeration, Chinese is commonly known as enumeration class, learn C + + and other languages of the people, should be to it knows. In the Java language Specification, however, it was introduced in the JDK version 5 and stored in the Java.lang package. In the Java version of the enum is essentially a syntactic sugar, which is declared in the following way:

1  Package  2publicenum  color{  3 4          5  6 7GREEN    8            

An enum is a keyword used to declare an enumeration, and the class that declares the definition implicitly inherits a parent class (java.lang.enum<e>), so the enumeration cannot be inherited, but the interface can still be implemented. The parent class has two private property name (the name of the enumeration type) and ordinal (the ordinal of the enumeration instance was created), exposed by name () and ordinal () respectively. Each enumeration instance defined in the enumeration type is mapped to the subclass of the enum, and the name of its instance and the order defined in the enumeration type are passed into the constructor protected Enum (String name, int ordinal).

2. If you want to understand the enum more clearly, you can use the Anti-compilation tool to decompile your own definition of the enumeration to a glance, it is a normal class, but the Java language Specification from the code point of view is limited, the execution of the JAVAP felix.fu.Color command is as follows:

1  Public Final classColorextendsjava.lang.enum{2      Public Static FinalColor RED;3      Public Static FinalColor BLUE;4      Public Static FinalColor BLACK;5      Public Static FinalColor YELLOW;6      Public Static FinalColor GREEN;7     Static {}; 8      Public Staticcolor[] VALUES ();9      Public StaticColor valueOf (java.lang.String);Ten}

3. If the defined enumeration has its own constructor, it must declare private.

Two. Usage
1. Usage Scenarios
(1) commonly used to classify constants of the same class
(2) When declaring an interface method, the input parameter type takes an enumeration more rigorously than the original type value constant.
(3) Constants are sometimes more than just a value, and may contain multiple attributes, which is a good time to enumerate
(4) A constant object needs to read its descriptive information or UI display information from the configuration file, which is also suitable for enumeration
(5) From the Java syntax level, enumerations can be used in switch and can be directly compared in the IF
(6) It is best to use the public final decoration when declaring enumeration properties, which is very convenient.
(7) When customizing enumerations, it is recommended not to use the own name () and ordinal () method return values to convert to the original value type, so that the business does not rely on its enumeration name and order, as follows:

1  Public enumColor {2RED (0), BLUE (1), BLACK (2), YELLOW (3), GREEN (4); 3      Public Final intvalue;4     /** 5      * @paramvalue6      */ 7     PrivateColor (intvalue) { 8          This. Value =value;9     } Ten      Public StaticColor getinstance (intvalue) {  One          for(Color code:values ()) { A             if(Code.value = =value) -                 returnCode; -         }  the         return NULL;  -     }  -}

2. Example: An enumeration-based simple exception framework is declared, using enumerations to implement

1  Public InterfaceExceptioncode {2     /** 3 * Return Exception code4      */ 5 String GetErrorCode (); 6     /** 7 * Return Exception description8      * @paramarray of placeholder values used to describe the args exception9      */     Ten String geterrorcause (Object ... args); One }  A  Public enumDbexceptioncodeImplementsExceptioncode { -Unique_key ("10001", "PRIMARY KEY constraint Error"),  -Foreign_key ("10002", "FOREIGN KEY constraint error");  the      Public FinalString ErrorCode; -      Public FinalString ErrorName; -     PrivateDbexceptioncode (String errorCode, String errorname) { -          This. ErrorCode =ErrorCode; +          This. ErrorName =ErrorName; -     }  + @Override A      PublicString GetErrorCode () { at         returnErrorCode; -     }  - @Override -      PublicString geterrorcause (Object ... args) { -         //TODO need to read from the configuration by ErrorCode -String Errorcause = "";  in         returnMessageformat.format (Errorcause, args); -     }  to }  +  Public classDbexceptionextendsRuntimeException { -     protectedString ErrorCode; the     protectedString Errorcause; *     /**  $ * Message format:BussinessErrorCode:BussinessErrorCause eg:10010: invalid barcode[1000052]Panax Notoginseng      *  -      * @paramerrorCode error Code of bussiness the      * @paramerrorcause error cause of bussiness +      * @paramcause A      */  the     protecteddbexception (String errorCode, string errorcause, Throwable cause) { +         Super(ErrorCode + ":" +errorcause, cause);  -          This. ErrorCode =ErrorCode; $          This. Errorcause =Errorcause; $     }  -      Publicdbexception (Exceptioncode exceptioncode, Object ... args) { -          This(Exceptioncode.geterrorcode (), Exceptioncode.geterrorcause (args)); the     }  -      Publicdbexception (throwable cause, Exceptioncode exceptioncode, Object ... args) {Wuyi          This(Exceptioncode.geterrorcode (), Exceptioncode.geterrorcause (args), cause); the     }  -      Publicdbexception (Exceptioncode exceptioncode, throwable cause) { Wu          This(Exceptioncode.geterrorcode (), exceptioncode.geterrorcause (), cause); -     }  About     protecteddbexception (String errorCode, String errorcause) { $          This(ErrorCode, Errorcause,NULL);  -     }  -     /**  -      * @returnThe errorCode A      */  +      PublicString GetErrorCode () { the         returnErrorCode; -     }  $     /**  the      * @returnThe errorcause the      */  the      PublicString Geterrorcause () { the         returnErrorcause; -     }  in}

Three. Cons: It's a bit of a hassle to convert to a primitive value.

Four. Typically define constant methods and enumerations to define constant method differences
The following may be a bit boring, but definitely worth a glimpse
1. Code:

1  Public class  2public     staticfinalint on = 13 Public     staticfinal Int off= 04

First, it is not type-safe. You have to make sure it's int.
Second, you have to make sure it's 0 and 1.
Finally, many times when you print out, you only see 1 and 0, but the person who does not see the code does not know your intentions, discarding all of your old public static final constants.

2. You can create an enum class that is considered an ordinary class. Except that it cannot inherit other classes. (Java is a single inheritance, it has inherited an enum), you can add other methods to override its own methods

The 3.switch () parameter can use enum
The 4.values () method is the static method that the compiler inserts into the enum definition, so when you convert an enum instance up to a parent enum, values () is inaccessible. Workaround: There is a getenumconstants () method in class, so even if the enum interface does not have the values () method, we can still get all the enum instances through the class object
5. You cannot inherit subclasses from an enum, and if you need to extend the elements in an enum, within an interface, create an enumeration that implements that interface to group the elements. The enumeration elements are grouped to be reached.
6. Use Enumset instead of logo. An enum requires that its members are unique, but the add element cannot be removed from the enum.
The 7.EnumMap key is an enum, and value is any other object.
8.enum allows programmers to write methods for EUNM instances. Therefore, each enum instance can be given a different behavior.
9. Use the Enum's responsibility chain (Chain of Responsibility). This is related to the design pattern of responsibility chain mode. Solve a problem in a number of different ways. Then link them together. When a request arrives, it traverses the chain until a solution in the chain can handle the request.
10. State machine using enum
11. Using the enum multi-channel distribution

Java enum class syntax and usage parsing

Related Article

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.