Enumerated types are part of the new Java 5 feature set. They are a special type of data that is special because they are a class type but have more special constraints than class types. But these constraints also contribute to the simplicity, security, and convenience of enumerated types.

▷ I will continue to study and revise this article

1. Enumeration class learning

1.1 Define enumerated classes

  • Enumeration classes can implement one or more interfaces. Enumeration classes defined using enum inherit from java.lang. enum by default, not Object by default, so enumeration classes cannot be shown to inherit from other parent classes. The java.lang.Enum class implements java.lang.Serializable and java.lang.Comparable interfaces. Enumeration classes defined using enum and not abstract use final qualifiers by default, so enumeration classes cannot be subclassed.
  • The constructor of an enumerated class can only use the private access-control character. If the constructor is omitted, the private modifier is used by default. If you force an access control character, only the private modifier can be specified.
  • All instances of an enumerated class must be explicitly listed on the first line of the enumerated class, or the enumerated class will never generate an instance. When these instances are listed, the public Static Final modifier is automatically added without the programmer having to add it explicitly.
  • Enumeration classes provide a default values() method that makes it easy to iterate over all enumeration values.

Define constants from Monday to Sunday as follows

//Day.class
// Enumeration type, using keyword enum
enum Day {
    MONDAY, TUESDAY, WEDNESDAY,
    THURSDAY, FRIDAY, SATURDAY, SUNDAY
}
Copy the code

Quite succinctly, the keyword we use to define enumeration types is enum, similar to the class keyword, except that the former defines enumeration types and the latter defines class types.

1.2 Implementation principle of enumeration classes

Now that we’ve looked at the definition and simple use of enumerated types, it’s worth looking at the basics of how enumerated types are implemented. In fact, after creating the enum type using the keyword enum and compiling it, the compiler generates an associated class for us that inherits the java.lang. enum class from the Java API, That is, creating an enumerated type with the keyword enum is actually a class type when compiled and inherits from the java.lang. enum class.

To decompile the day.class file:

// Decompile day.class
final class Day extends Enum
{
    // Static values() method the compiler added for us
    public static Day[] values()
    {
        return (Day[])$VALUES.clone();
    }
    // The compiler added a static valueOf() method for us. Note that it indirectly calls the valueOf method of the Enum class
    public static Day valueOf(String s)
    {
        return (Day)Enum.valueOf(com/zejian/enumdemo/Day, s);
    }
    // Private constructor
    private Day(String s, int i)
    {
        super(s, i);
    }
     // The seven enumerated instances defined earlier
    public static final Day MONDAY;
    public static final Day TUESDAY;
    public static final Day WEDNESDAY;
    public static final Day THURSDAY;
    public static final Day FRIDAY;
    public static final Day SATURDAY;
    public static final Day SUNDAY;
    private static final Day $VALUES[];

    static 
    {    
        // instantiate the enumeration instance
        MONDAY = new Day("MONDAY".0);
        TUESDAY = new Day("TUESDAY".1);
        WEDNESDAY = new Day("WEDNESDAY".2);
        THURSDAY = new Day("THURSDAY".3);
        FRIDAY = new Day("FRIDAY".4);
        SATURDAY = new Day("SATURDAY".5);
        SUNDAY = new Day("SUNDAY".6);
        $VALUES = (newDay[] { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY }); }}Copy the code
  • We can see from the decomcompiled code that the compiler did help us generate a Day class (note that the class is final and will not be inherited) and that the class inherits fromjava.lang.EnumClass, which is an abstract class (we’ll look at the main methods in this class later).
  • (2) in addition, the compiler also help us to generate the seven Day types of instance objects correspond enumeration defined in the 7 date, this also shows our previous use keyword enum definition of Day type the date of each enumerated constants are real Day instance objects, it’s just on behalf of the content is not the same. Note that the compiler also generates two static methods for us, respectivelyValues () and the valueOf ().
  • At compile time, an enum type defined with the keyword enum will also be converted into a real class in which there will be corresponding instance objects for each variable defined in the enum type, as described aboveMONDAYMapping of enumeration typespublic static final Day MONDAY;, and the compiler creates two methods for the class, respectivelyValues () and the valueOf (). We believe that the implementation principle of enumeration is also quite clear. Let’s take a closer look at the java.lang.enum class and what values() and valueOf() are used for.

1.3 Common methods of enumeration

2. Enumeration class usage

2.1 constant

There are three ways to realize constant in the system: interface constant, class constant and enumeration constant

2.1.1 Interface Constants

Java swing, for example, has a SwingConstant:

public interface SwingConstants {

        /** * The central position in an area. Used for * both compass-direction constants (NORTH, etc.) * and box-orientation constants (TOP, etc.). */
        public static final int CENTER  = 0;

        // 
        // Box-orientation constant used to specify locations in a box.
        //
        /** * Box-orientation constant used to specify the top of a box. */
        public static final int TOP     = 1;
        /** * Box-orientation constant used to specify the left side of a box. */
        public static final int LEFT    = 2;
       
       / /... Omit other code
   }
Copy the code

2.1.2 class constant

Defaultvalues.default_ap (); defaultvalues.default_ap If there are a lot of constants, it doesn’t feel very friendly to put all of them in one interface.

/** * System default value ** /
public class DefaultValues {

	/** * Default password */
	public static final String DEFAULT_PASSWORD = "000000";
	/** * Default user type */
	public static final String DEFAULT_USER_TYPE = UserType.NormalUser.value();	
	/** * Gets the API name */ by default
	public static final String DEFAULT_API = "api";
	
	/** * Default system character encoding */
	public static final String DEFAULT_ENCODING = "UTF-8";
	
	/** Cluster size */
	public static final  long CLUSTER_SIZE = 1000;
}
Copy the code

Pros and cons: The company’s interface constants define static internal classes in the interface, which can further classify constant classes for different functions. Different function constants are placed in the inner class of the interface, through the different inner class can clearly know the meaning of a constant.

public class Constants {
	public static class MimeType{
		public static final String BIN = "application/octet-stream";
		public static final String CSS = "text/css";
		public static final String DOC = "application/msword";
		public static final String DOCX = "";
		public static final String EXE = "application/octet-stream";
		public static final String GTAR = "application/x-gtar";
		public static final String GZ = "application/x-gzip";
		public static final String HTM = "text/html; charset=utf-8";
		public static final String ICO = "image/x-icon";
		public static final String JPEG = "image/jpeg";
		public static final String JPG = "image/jpeg";
		public static final String JS = "application/x-javascript; charset=utf-8";
		public static final String JSON = "application/json; charset=utf-8";
		public static final String FORM = "application/x-www-form-urlencoded; charset=UTF-8";
		public static final String MULTIPART = "multipart/form-data; charset=UTF-8";
		public static final String MHT = "message/rfc822";
		public static final String MHTML = "message/rfc822";
		public static final String MOV = "video/quicktime";
		public static final String MP3 = "audio/mpeg";
		public static final String MPE = "video/mpeg";
		public static final String MPEG = "video/mpeg";
		public static final String MPG = "video/mpeg";
		public static final String PDF = "application/pdf";
		public static final String PPT = "application/vnd.ms-powerpoint";
		public static final String RTF = "application/rtf";
		public static final String SWF = "application/x-shockwave-flash";
		public static final String TAR = "application/x-tar";
		public static final String TXT = "text/plain; charset=utf-8";
		public static final String WAV = "audio/x-wav";
		public static final String XML = "text/xml; charset=utf-8";
		public static final String ZIP = "application/zip";
		
	}
	
	public static class DataState{
		public static final String FLAG_REMOVE = "Y";
		public static final String FLAG_NORMAL = "N";
	}
	
	/** * Application server instance running status */
	public static class ServerASInstanceState{
		public static final int RUNNING = 1;
		public static final int SHUT_OFF = 2;
	}
	/** * WebServices interface analysis */
	public static class WebServicesType{
		/** receive data first, in the case of the return interface interface **/ 
		public static final String IN_OUT = "IO";
		/** The interface that sends data requests first and returns data later **/ 
		public static final String OUT_IN = "OI";
		/** Only send data interface **/ 
		public static final String OUT= "O";
		/** The interface that only receives data **/ 
		public static final String IN = "I";
	}
	
	/** * Task scheduling uses */
	public static class TaskScheduling{
		/** Task ID **/ 
		public static final String TASK_ID = "taskID";
		/** Task URL **/ 
		public static final String TASK_URI = "taskURI";
		/** Task URL **/ 
		public static final String TASK_NAME = "taskName";
		/** Target server IP address **/ 
		public static final String TASK_SERVER_IP = "taskServerIp";
		/** Target server IP address **/ 
		public static final String TASK_SERVER_PORT = "taskServerPort";
		
		/** Task status Enable **/
		public static final int TASK_ENABLED = 1;
		
		/** Task status disabled **/
		public static final int TASK_DISABLE = 0;
		
		/** Annual tasks **/
		public static final int TYPE_EVERY_YEAR= 1;
		
		/** Monthly tasks **/
		public static final int TYPE_EVERY_MONTH = 2;
		
		/** Daily tasks **/
		public static final int TYPE_EVERY_DAY = 3;
		
		/** Weekly tasks **/
		public static final int TYPE_EVERY_WEEK = 4;
		
		/** Single task **/
		public static final int TYPE_SINGLE = 5; }}Copy the code

Although there are enumerations, probably because of designer habits, there are many people who use class constants. They define class constants with a Map

that encapsulates the information about the constant. In static code blocks, classes are initialized with a put. Responsecode.resp_info. get(“DATABASE_EXCEPTION”); Since the project is separated from the front and back, we need to write the status code in the interface document, and we need to write the corresponding message of the status code, and our response class RespInfo has the message property, which holds the corresponding information of the status code in the constant class.
,>

public class ResponseCode {

    /** The system is processing properly */
    public static final int SUCCESS_HEAD = 0;

    /** The system handles an unknown exception */
    public static final int EXCEPTION_HEAD = 1;

    /** JSON parsing error */
    public static final int JSON_RESOLVE = 2;

    /** Type mismatch */
    public static final int TRANSTYPE_NO = 3;

    /** head-messageid is not assigned */
    public static final int HEAD_messageID = 4;

    /** head-timestamp unassigned */
    public static final int HEAD_timeStamp = 5;

    /** Head - messengerID no value */
    public static final int HEAD_messengerID = 6;

    /** head-transactionType unassigned */
    public static final int HEAD_transactionType = 7;

    /** The digest verification fails */
    public static final int HEAD_DIGEST = 8;
    
    /** SRC check fails */
    public static final int HEAD_SRC_NULL = 10;
    
    /** The protocol contains invalid characters */
    public static final int ILLEGAL_MESSAGE = 11;

    /** Database exception */
    public static final int DATABASE_EXCEPTION = 9;
    public static final Map<Integer, String> RESP_INFO = new HashMap<Integer, String>();

    static {
        / / Head
        RESP_INFO.put(SUCCESS_HEAD, "System processing normal");
        RESP_INFO.put(EXCEPTION_HEAD, "System handles unknown exceptions");
        RESP_INFO.put(JSON_RESOLVE, "JSON parsing error");
        RESP_INFO.put(TRANSTYPE_NO, "Type mismatch");
        RESP_INFO.put(HEAD_messageID, "MessageID not assigned");
        RESP_INFO.put(HEAD_timeStamp, "TimeStamp not assigned");
        RESP_INFO.put(HEAD_messengerID, "MessengerID not assigned");
        RESP_INFO.put(HEAD_transactionType, "TransactionType not assigned");
        RESP_INFO.put(HEAD_DIGEST, "Digest verification failed");
        RESP_INFO.put(DATABASE_EXCEPTION, "Database exception");
        RESP_INFO.put(HEAD_SRC_NULL, "SRC not assigned");
        RESP_INFO.put(ILLEGAL_MESSAGE, "Protocol contains illegal characters"); }}Copy the code

2.1.3 Enumerating constants

All enumerated classes are subclasses of the Enum class, just like Object, except that they are not written out, so you can enumerate classes that can call Enum methods. Note that properties are separated by commas, and only properties without methods are followed by a semicolon or not.

(1)

public enum StateType {
	/** * Successfully returns status */
	OK(200."OK"), 
	
	/** * Request format error */
	BAD_REQUEST(400."bad request"),
	/** * not authorized */
	UNAUTHORIZED(401."unauthorized"),
	/** * no permission */
	FORBIDDEN(403."forbidden"),
	
	/** * The requested resource does not exist */
	NOT_FOUND(404."not found"),
	/** * This HTTP method is not allowed */
	NOT_ALLOWED(405."method not allowed"),
	/** * Request processing error */
	PROCESSING_EXCEPTION(406."Handling Exceptions"),
	/** ** Request processing not completed */
	PROCESSING_UNFINISHED(407."To deal with unfinished"),
	
	/** * Login expired */
	BEOVERDUE(408."Be overdue"),
	
	/** * The user is not logged in */
	NOT_LOGIN(409."Not logged in"),
	
	/** * The resource corresponding to this URL is not available */
	GONE(410."gone"),
	/** * Request type error */
	UNSUPPORTED_MEDIA_TYPE(415."unsupported media type"),
	/** ** * is used to verify errors
	UNPROCESSABLE_ENTITY(422."unprocessable entity"),
	/** * too many requests */
	TOO_MANY_REQUEST(429."too many request");

	private int code;
	private String value = null;

	private StateType(int code,String value) {
		this.code = code;
		this.value = value;
	}

	public String value(a) {
		return this.value;
	}

	public int getCode(a) {
		return code;
	}

	public static Boolean isValidateStateType(String... stateType) {
		for (int i = 0; i < stateType.length; i++) {
			StateType [] value = StateType.values();
			boolean falg = false;
			for(StateType type : value) {
				if(type.value.equals(stateType[i])) {
					falg = true; }}if(! falg) {returnfalg; }}return true; }}/ * * / use
public static void main(String[] args) {
	System.out.println("Status code:+StateType.getCode());
        System.out.println(Error message:+StateType.getValue());
}
Copy the code

(2)

public enum Level {
	/** * the first layer */
	One(1),
	/** * layer 2 */
	Two(2),
	/** ** layer 3 */
	Three(3),
	/** ** /
	Four(4),
	/** ** /
	Five(5);
	
	private int value;
	
	Level(int value) {
		this.value = value;
	}
	
	public int value(a) {
		return this.value;
	}
	
	public static Boolean isValidateLevel(int level) {
		Level [] value = Level.values();
		boolean falg = false;
		for (Level pl : value){
			if(pl.value == level){
				falg = true; }}returnfalg; }}/ * * / use
public static void main(String[] args) {
	System.out.println(Floor:+Level.Three);
}
Copy the code

2.2 Switch with enumeration Classes

Switch statements prior to JDK1.6 only supported int,char, and enum types. Using enumerations makes our code more readable.

Enumeration is the declaration of a named set of constants. When a variable has several possible values, it can be defined as an enumeration type. Enumeration lists the values of a variable one by one. The values of a variable are limited to the range of listed values.

△ Note: Enumeration is just an enumeration type and cannot be an assignment operation. GREEN The default value is 0, but GREEN cannot =0 because the data type is different. Enumeration variable is not directly assigned, the default value is equal to the previous variable value plus one, the default starting value is 0.

enum Signal { 
 GREEN, YELLOW, RED 
} 
public class TrafficLight { 
 Signal color = Signal.RED; 
 public void change(a) { 
  switch (color) { 
  case RED: 
   color = Signal.GREEN; 
   break; 
  case YELLOW: 
   color = Signal.RED; 
   break; 
  case GREEN: 
   color = Signal.YELLOW; 
   break; }}}Copy the code

2.3 Adding new methods to enumerations

If you want to customize your own methods, you must add a semicolon (“; “) at the end of the enum instance sequence. ), Java requires that you define a Java instance first.

public enum ChannelEnum {

    MSG_CENTER_CHANNEL1("msg_center_channel1"),
    MSG_CENTER_CHANNEL("msg_center_channel");

    private String channel = null;

    private ChannelEnum(String channel) {
        this.channel = channel;
    }

    public String getChannel(a) {
        return this.channel; }}Copy the code

2.4 Interface Implementation

  • All enumerations inherit from the java.lang.Enum class. Because Java does not support multiple inheritance, enumeration objects can no longer inherit from other classes.
  • If an enumeration class implements a method in an interface, each enumerated value behaves the same way when calling the method (because the method body is exactly the same). If you need each enumeration value to behave differently when calling the method, you can have each enumeration value implement the method separately, with each enumeration value providing a different implementation so that different enumeration values can behave differently when calling the method.
public interface Behaviour {  
    void print(a);  
    String getInfo(a);  
}  
public enum Color implements Behaviour{  
    RED("Red".1), GREEN("Green".2), BLANK("White".3), YELLO("Yellow".4);  
    // Member variables
    private String name;  
    private int index;  
    // constructor
    private Color(String name, int index) {  
        this.name = name;  
        this.index = index;  
    }  
// Interface method
    @Override  
    public String getInfo(a) {  
        return this.name;  
    }  
    // Interface method
    @Override  
    public void print(a) {  
        System.out.println(this.index+":"+this.name); }}Copy the code

2.5 Using Interfaces to organize enumerations

public interface Food {
    enum Coffee implements Food{  
        BLACK_COFFEE,DECAF_COFFEE,LATTE,CAPPUCCINO  
    }  
    enum Dessert implements Food{  
        FRUIT, CAKE, GELATO  
    }  
}
Copy the code

Address:

  • 1) blog.csdn.net/javazejian/…
  • (2) blog.csdn.net/qq_27093465…
  • (3) www.cnblogs.com/lihaoyang/p…
  • (4) segmentfault.com/a/119000000…