The article is simple. I believe that the use of Java Enum enumeration can be found on many websites. Some things I did not find at the beginning, so I wrote this article, for example:
In most cases, an enumeration is written for an enumeration and then an example is started to switch. However, I would like to say that the data from the source in my code is not likely to be enumeration, which is usually a string or number, for example, after an SQL statement is parsed, I first determine the SQL type. by intercepting the SQL token, it may be select, delete, update, insert, alter, etc., but they are all strings, in this case, I want to use enumeration, and I will not be able to convert the string into enumeration. In this case, I will retrieve the data from the database and determine the data based on some types and import the data from the page, perform different operations based on different types, but they are all strings, not enumeration. Unfortunately, I rarely see someone writing this thing. So I write it down and hope someone can use it.
Why do I need enumeration first? When can we use enumeration better? What are the advantages of enumeration?
I think it is better to use enumeration when you are in a category class and can list non-changing types to guide the program to route to different places;
It sounds a bit difficult, but an example may be clear, for example:
We can list what we do on a daily basis:
Work, meeting, eating, sleeping, etc.
We can list the locations of the hospital's five departments that need to be inspected:
Eyes, nose, ears, Mouth, etc.
These areCan be listedAndWe need to do different things.;
Of course you can say:
1. You can use a dynamic method for dispatching through the configuration file or annotation;
2. constants can be used to achieve similar results;
3. It is expressed directly through the string equals and expressed using if else.
It is flexible and easy to modify if you use the configuration addition method for allocation. However, if you use this method for many parameters that are not frequently modified, the configuration burden is often increased, when you need to view the system logic, you need to view the configuration and code again. However, if the parameter can be dynamically changed, the configuration is the correct choice;
The use of constants is usually a number in the case of switch. in Java, a string cannot be used as a switch case. The purpose of using constants is as follows: Case 1, Case 2... this increases readability, but String data is also troublesome. Unless it is mapped again, it is not necessary. In fact, enumerations are similar to ing for you once, it's just encapsulating the code. Now that he's finished and syntactically supported, why not! Secondly, although constants increase readability, they do not have the concepts of categories and management types. That is, an enumeration definition defines a category, it is good to list the things required for this range, while constants are usually some of their own defined pools and put them in some public classes or random definitions, which are relatively scattered, in addition, the enumeration is clearly defined when the switch is used, and the case is within the scope of the lock list, which can control the system and increase readability, in addition, you can view the enumerated information of this category at any time to see the effect of the configuration file. However, back to that sentence, if the parameter is variable, it is not suitable for enumeration, enumeration must be enumerative, or the scope of the current system consideration can be enumerated. For example, many of the five official departments in the above hospital may not be listed, but the current hospital only processes several parts, this is the principle of not processing anything else. What is variable? For example, if URL parameters are assigned to the corresponding method, it is impossible for everyone to add an enumeration and a case to the logic, in this case, it is better to use [configuration + dynamic method Assignment]. Of course, the configuration can only use a file or annotation.
The most common thing is to use the string equals and if else for implementation, the equals of string matching must be compared to each character in each matching. If your code contains a large number of loops, the performance is not very good. The rest will be more clear by looking at the above descriptions;
Secondly, enumeration provides a type of management component to improve the object-oriented system, so that some types of management can be configured and managed, where enumeration is used, you can find the ones that have been processed and those that have not been processed along the enumeration definition, which is difficult to achieve. For example, 10 types of database operation types are defined, during the determination process, enumeration can be viewed as a configuration file and managed in a very simple way.
Finally, enumeration is a singleton. The comparison performance is similar to the numerical performance, which can be both readable and performance.
Let's first define a simple enumeration (here is just an example, we will simply define three variables ):
public enum SqlTypeEnum { INSERT , UPDATE , DELETE , SELECT}
After the SQL statement is parsed, a token is obtained. How can we obtain the token enumeration?
Obtain the following information:
String token = "select";SqlTypeEnum sqlTypeEnum = SqlTypeEnum.valueOf(token.toUpperCase());
If not, Java throws an exception:IllegalargumentexceptionNo Enum const class sqltypeenum. xxx
I doReason for capital ProcessingThe reason is that the enumeration is in upper case (of course, if your enumeration is in lower case, you will be in lower case, but it is troublesome to mix and write). In fact, valueof calls the underlying map of enumeration:
This method is called:
Therefore, it is also a hashmap internally!
After obtaining this information, you can perform the following operations:
Switch (sqltypeenum) {case insert: processing insert logic; break; Case Delete: Processing Delete logic; break ;....}
Okay. Sometimes we may not want to directly use strings such as insert and update for interaction, because many naming rules are required;
For example, define some user operation types:
1. Save User Information
2. Get basic user information by ID
3. Get the user list
4. delete user information by ID
And so on.
We may define an enumeration as follows:
public enum UserOptionEnum { SAVE_USER, GET_USER_BY_ID, GET_USER_LIST, DELETE_USER_BY_ID}
However, system methods and keyword configurations are usually written as follows:
Saveuser, getuserbyid, getuserbyid, and deleteuserbyid
Of course, each has its own rules, but you don't want to do this in the middle layer of the ing. On the one hand, you may compromise. Either the enumeration names are all replaced, which seems strange, or the method names are all replaced, even more strange, you can either map it yourself. It's a little troublesome. Isn't it actually a problem?
First, we will write a method to convert the enumerated underline-style data into a hump, put it in a stringutils:
public static String convertDbStyleToJavaStyle(String dbStyleString , boolean firstUpper) { dbStyleString = dbStyleString.toLowerCase(); String []tokens = dbStyleString.split("_"); StringBuilder stringBuilder = new StringBuilder(128); int length = 0; for(String token : tokens) { if(StringUtils.isNotBlank(token)) { if(length == 0 && !firstUpper) { stringBuilder.append(token); }else { char c = token.charAt(0); if(c >= 'a' || c <= 'z') c = (char)(c - 32); stringBuilder.append(c); stringBuilder.append(token.substring(1)); } } ++length; } return stringBuilder.toString(); }
Reload a method:
public static String convertDbStyleToJavaLocalStyle(String dbStyleString) { return convertDbStyleToJavaStyle(dbStyleString , false); }
Then define enumeration:
public enum UserOptionEnum { SAVE_USER, GET_USER_BY_ID, GET_USER_LIST, DELETE_USER_BY_ID; private final static Map<String , UserOptionEnum> ENUM_MAP = new HashMap<String, UserOptionEnum>(64); static { for(UserOptionEnum v : values()) { ENUM_MAP.put(v.toString() , v); } } public staticUserOptionEnum fromString(String v) { UserOptionEnum userOptionEnum = ENUM_MAP.get(v); return userOptionEnum == null ? DEFAULT :userOptionEnum; } public String toString() { String stringValue = super.toString(); return StringUtil.convertDbStyleToJavaLocalStyle(stringValue); }}
OK, so that if the parameter is saveuser, use:
String event = "saveuser"; // If useroptionenum Enum = useroptionenum. fromstring (event) is obtained here );
In fact, I made a hashmap myself. I added a fromstring here, because enumeration has some limitations and some methods won't be overwritten, such as the valueof method.
In fact, there is nothing to talk about. Let's talk about adding some custom variables to enumeration. In fact, apart from being single-instance enumeration, the rest are similar to common classes, it can also have a constructor, but not by default. It can also provide custom variables and then obtain the set and get methods. However, if there is a set, the thread is not safe. Pay attention to this. Therefore, the constructor is generally written as follows:
Public Enum sqltypeenum {insert ("insert into"), delete ("delete from ")...... omitted; private string name; // custom variable private sqltypeenum (string name) {This. name = Name;} Public String getname () {return name;} Public String tostring () {return name + ""; // override tostring method} // public void setname (string name) {This. name = Name ;}}
Call:
SqlTypeEnum sqlTypeEnum = SqlTypeEnum.valueOf("INSERT");System.out.println(sqlTypeEnum);System.out.println(sqlTypeEnum.getName());
Not recommendedAlso called:
Sqltypeenum. setname ("I rely on ");
In another thread:
SqlTypeEnum sqlTypeEnum = SqlTypeEnum.valueOf("INSERT");System.out.println(sqlTypeEnum);System.out.println(sqlTypeEnum.getName());
The result was changed!