In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article introduces the relevant knowledge of "what is the use of Java enumeration class". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
What are the characteristics of an enumeration class
Create an enumerated class for ColorEnum, compile it, and then decompile it to see what happens to it.
Public enum ColorEnum {RED,GREEN,BULE;}
Use the command javac ColorEnum.java to compile and generate the class file, and then decompile it with the command javap-p ColorEnum.class.
Remove the package name, and the decompiled content is as follows:
Public final class ColorEnum extends Enum {public static final ColorEnum GREEN; public static final ColorEnum BULE; private static final ColorEnum [] $VALUES; public static ColorEnum [] values (); public static ColorEnum valueOf (java.lang.String); private ColorEnum (); static {};}
Enumerated classes are modified by final, so enumerated classes cannot be inherited
Enumerated classes inherit Enum classes by default, and java does not support multiple inheritance, so enumerated classes cannot inherit other classes.
The constructor of an enumerated class is private-decorated, so other classes cannot get objects through the constructor
The member variables of enumerated classes are static-decorated and can be named with the class name. Variable to get the object
The values () method gets all the enumerated instances
ValueOf (java.lang.String) is to obtain the corresponding instance according to the name.
Two enumerations create thread-safe singleton mode
Public enum SingletonEnum {INSTANCE; public void doSomething () {/ / dosomething... }}
Such a singleton pattern is created, and the object is obtained through SingletonEnum.INSTANCE.
2.1 Serialization makes singleton mode unsafe
If a class implements a serialization interface, it may break the singleton. Each time a serialized instance object is deserialized, a new instance is created.
Enumerated serialization is guaranteed by JVM, and each enumerated type and defined enumerated variables are unique in JVM. Java makes a special provision on the serialization and deserialization of enumerated types: when serializing, Java only outputs the name property of enumerated objects to the results, while deserializing looks up enumerated objects by name through java.lang.Enum 's valueOf method. At the same time, the compiler does not allow any customization of this serialization mechanism and disables methods such as writeObject, readObject, readObjectNoData, writeReplace, and readResolve, thus ensuring the uniqueness of enumerated instances.
2.2 reflection makes singleton mode unsafe
The reflection forcibly invokes the private constructor to generate the instance object, making the singleton mode unsafe.
Class aClass = Class.forName ("xx.xx.xx"); Constructor constructor = aClass.getDeclaredConstructor (String.class); SingletonEnum singleton = (SingletonEnum) constructor.newInstance ("Java journey")
But singletons created with enumerations don't have to think about this at all. Take a look at the source code of newInstance!
Public T newInstance (Object... Initargs) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {if (! override) {if (! Reflection.quickCheckMemberAccess (clazz, modifiers)) {Class caller = Reflection.getCallerClass (); checkAccess (caller, clazz, null, modifiers);}} / / if it is an enumerated type, throw an exception directly to prevent the creation of an instance object! If ((clazz.getModifiers () & Modifier.ENUM)! = 0) throw new IllegalArgumentException ("Cannot reflectively create enum objects"); ConstructorAccessor ca = constructorAccessor; / / read volatile if (ca = = null) {ca = acquireConstructorAccessor ();} @ SuppressWarnings ("unchecked") T inst = (T) ca.newInstance (initargs); return inst;}
If it is an enum type, the exception Cannot reflectively create enum objects is thrown directly, and the instance object cannot be created through reflection!
Third, eliminate if/else by enumeration
If you want to write a set of encryption interfaces, give them to Mini Program, app and web respectively, but the encryption methods of these three clients are different. In general, we will pass a type type to determine the source, and then call the corresponding decryption method. The code is as follows:
If ("WEIXIN" .equals (type)) {/ / dosomething} else if ("APP" .equals (type)) {/ / dosomething} else if ("WEB" .equals (type)) {/ / dosomething}
Now use enumerations to eliminate these if/else.
Write an encryption interface with two methods: encryption and decryption. Then use different algorithms to implement this interface to complete encryption and decryption.
Public interface Util {/ / decrypt String decrypt (); / / encrypt String encrypt ();}
Create an enumeration class to implement this interface
Public enum UtilEnum implements Util {WEIXIN {@ Override public String decrypt () {return "Wechat decryption";} @ Override public String encrypt () {return "Wechat encryption";}}, APP {@ Override public String decrypt () {return "app decryption" @ Override public String encrypt () {return "app encryption";}}, WEB {@ Override public String decrypt () {return "web decryption";} @ Override public String encrypt () {return "web encryption";}} }
Finally, after you get the type, just call the decryption method directly.
String decryptMessage = UtilEnum.valueOf (type). Decrypt ()
In the future, if you add another encryption method, you only need to modify the enumeration class above, and the business code does not need to be changed.
These are the two more advanced uses of the enumeration class.
This is the end of the content of "what is the use of the Java enumeration class". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.