1. Use of enumeration classes
1.1. Understanding of enumeration classes
- Class has only a limited number of objects, which is uncertain. Examples are as follows:
- Monday, Sunday
- Gender: man (male), woman (female)
- Season: Spring Festival... Winter
- Payment methods: Cash (cash), WeChatPay (WeChat), Alipay (Alipay), BankCard (bank card), CreditCard (credit card).
- Employment status: Busy, Free, Vocation, Dimission
- Order status: unpaid, Paid, Delivered, Return, Checked, Fulfilled
- Thread status: create, ready, running, blocking, dead
- Enumeration classes are strongly recommended when you need to define a set of constants
- Implementation of enumeration class
- JDK1. You need to customize the enumeration class before 5
- The enum keyword added in JDK 1.5 is used to define enumeration classes
- If enumeration has only one object, it can be used as an implementation of the singleton mode.
1.2. User defined enumeration class
- Enumeration class properties
- The properties of enumeration class objects should not be allowed to be changed, so private final should be used
- The private final decorated property of an enumeration class should be assigned a value in the constructor
- If the enumeration class explicitly defines a constructor with parameters, the corresponding incoming parameters must also be used when listing the enumeration values
public class SeasonTest { public static void main(String[] args) { Season spring = Season.SPRING; System.out.println(spring); } } //Custom enumeration class class Season{ //1. Declare the attribute of Season object: private final modifier private final String seasonName; private final String seasonDesc; //2. Privatize the constructor of the class and assign a value to the object attribute private Season(String seasonName,String seasonDesc){ this.seasonName = seasonName; this.seasonDesc = seasonDesc; } //3. Provide multiple objects of the current enumeration class public static final Season SPRING = new Season("spring","Recovery of all things"); public static final Season SUMMER = new Season("summer","Scorching sun"); public static final Season AUTUMN = new Season("autumn","Jinqiu songshuang"); public static final Season WINTER = new Season("winter","snow gleams white"); //4. Other requirements: get the properties of enumeration objects public String getSeasonName() { return seasonName; } public String getSeasonDesc() { return seasonDesc; } //4. Other claims 1: toString() @Override public String toString() { return "Season{" + "seasonName='" + seasonName + '\'' + ", seasonDesc='" + seasonDesc + '\'' + '}'; } }
1.3. Use enum keyword to define enumeration class
- instructions
- Enum classes defined with enum inherit Java. Net by default Lang. enum class, so you can't inherit other classes
- The constructor of an enumeration class can only use the private permission modifier
- All instances of an enumeration class must be explicitly listed in the enumeration class (, delimited; end). The public static final modifier will be automatically added to the listed instances
- The enumeration class object must be declared on the first line of the enumeration class
- In JDK 1.5, the Enum class object defined by Enum can be used as the expression in the switch expression. The case clause can directly use the name of the Enum value without adding an Enum class as a qualification.
/** * Define enumeration classes using enum keyword * Note: the defined enumeration class inherits from Java. Net by default Lang. enum class */ public class SeasonTest1 { public static void main(String[] args) { Season1 summer = Season1.SUMMER; //toString(): System.out.println(summer.toString()); System.out.println(Season1.class.getSuperclass()); } } //Enum classes using enum keyword enum Season1{ //1. Provide the object of the current enumeration class. Multiple objects are separated by "," and the end object is ";" end SPRING("spring","Recovery of all things"), SUMMER("summer","Scorching sun"), AUTUMN("autumn","Jinqiu songshuang"), WINTER("winter","snow gleams white"); //2. Declare the attribute of Season object: private final modifier private final String seasonName; private final String seasonDesc; //3. Privatize the constructor of the class and assign a value to the object attribute private Season1(String seasonName,String seasonDesc){ this.seasonName = seasonName; this.seasonDesc = seasonDesc; } //4. Other requirements: get the properties of enumeration objects public String getSeasonName() { return seasonName; } public String getSeasonDesc() { return seasonDesc; } //4. Other claims 1: toString() // @Override // public String toString() { // return "Season{" + // "seasonName='" + seasonName + '\'' + // ", seasonDesc='" + seasonDesc + '\'' + // '}'; // } }
1.4 common methods in Enum class
- Main methods of Enum class
- values() method: returns an array of objects of enumeration type. This method can easily traverse all enumeration values.
- valueOf(String str): you can convert a string into a corresponding enumeration class object. The required string must be the name of an enumeration class object. If not, there will be a runtime exception: IllegalArgumentException.
- toString(): returns the name of the object constant of the current enumeration class
/** * Define enumeration classes using enum keyword * Note: the defined enumeration class inherits from Java. Net by default Lang. enum class * * 3, Common methods of Enum class * values()Method: returns an array of objects of enumeration type. This method can easily traverse all enumeration values. * valueOf(String str): You can convert a string to the corresponding enumeration class object. The required string must be the name of an enumeration class object. If not, there will be a runtime exception: IllegalArgumentException. * toString(): Returns the name of the object constant of the current enumeration class */ public class SeasonTest1 { public static void main(String[] args) { Season1 summer = Season1.SUMMER; //toString(): System.out.println(summer.toString()); // System.out.println(Season1.class.getSuperclass()); System.out.println("**************************"); //values(): returns an array of all enumeration class objects Season1[] values = Season1.values(); for(int i = 0;i < values.length;i++){ System.out.println(values[i]); } System.out.println("****************************"); Thread.State[] values1 = Thread.State.values(); for(int i = 0;i < values1.length;i++){ System.out.println(values1[i]); } //valueOf(String objName): returns the object whose object name is objName in the enumeration class. Season1 winter = Season1.valueOf("WINTER"); //If there is no enumeration class object of objName, throw an exception: IllegalArgumentException // Season1 winter = Season1.valueOf("WINTER1"); System.out.println(winter); } } //Enum classes using enum keyword enum Season1{ //1. Provide the object of the current enumeration class. Multiple objects are separated by "," and the end object is ";" end SPRING("spring","Recovery of all things"), SUMMER("summer","Scorching sun"), AUTUMN("autumn","Jinqiu songshuang"), WINTER("winter","snow gleams white"); //2. Declare the attribute of Season object: private final modifier private final String seasonName; private final String seasonDesc; //3. Privatize the constructor of the class and assign a value to the object attribute private Season1(String seasonName,String seasonDesc){ this.seasonName = seasonName; this.seasonDesc = seasonDesc; } //4. Other requirements: get the properties of enumeration objects public String getSeasonName() { return seasonName; } public String getSeasonDesc() { return seasonDesc; } //4. Other claims 1: toString() // @Override // public String toString() { // return "Season{" + // "seasonName='" + seasonName + '\'' + // ", seasonDesc='" + seasonDesc + '\'' + // '}'; // } }
1.5. Use enum keyword defined enumeration class to implement interface
- The implementation of the interface using the enum class defined by the enum keyword
- Scenario 1: implement the interface and implement the abstract method in the enum class
- Case 2: let the objects of the enumeration class implement the abstract methods in the interface respectively
/** * Use enum keyword to define enumeration class * Note: the defined enumeration class inherits from Java. Net by default Lang. enum class */ public class SeasonTest1 { public static void main(String[] args) { //values(): returns an array of all enumeration class objects Season1[] values = Season1.values(); for(int i = 0;i < values.length;i++){ System.out.println(values[i]); values[i].show(); } //valueOf(String objName): returns the object whose object name is objName in the enumeration class. Season1 winter = Season1.valueOf("WINTER"); winter.show(); } } interface Info{ void show(); } //Enum classes using enum keyword enum Season1 implements Info{ //1. Provide the object of the current enumeration class. Multiple objects are separated by "," and the end object is ";" end SPRING("spring","in the warm spring , flowers are coming out with a rush"){ @Override public void show() { System.out.println("The beginning of a new year and the recovery of all things"); } }, SUMMER("summer","Summer heat"){ @Override public void show() { System.out.println("Cicadas sound in bursts and the hot sun is in the sky"); } }, AUTUMN("autumn","fresh autumn weather"){ @Override public void show() { System.out.println("The sky is high, the air is clear, and the golden osmanthus fragrance"); } }, WINTER("winter","a world of ice and snow"){ @Override public void show() { System.out.println("Cold winter and the last month, dripping water turns into ice"); } }; //2. Declare the attribute of Season object: private final modifier private final String seasonName; private final String seasonDesc; //3. Privatize the constructor of the class and assign a value to the object attribute private Season1(String seasonName,String seasonDesc){ this.seasonName = seasonName; this.seasonDesc = seasonDesc; } //4. Other requirements: get the properties of enumeration objects public String getSeasonName() { return seasonName; } public String getSeasonDesc() { return seasonDesc; } //4. Other claims 1: toString() // @Override // public String toString() { // return "Season{" + // "seasonName='" + seasonName + '\'' + // ", seasonDesc='" + seasonDesc + '\'' + // '}'; // } // @Override // public void show() { // System.out.println("this is a season"); // } }
2. Use of annotations
2.1 understanding of notes
- Since JDK 5.0, Java has added support for metadata, that is, annotation
- Annotation is actually a special tag in the code. These tags can be read and processed during compilation, class loading and runtime. By using annotation, programmers can embed some supplementary information in the source file without changing the original logic. Code analysis tools, development tools and deployment tools can be verified or deployed through these supplementary information.
- Annotation can be used like modifiers to modify the declarations of packages, classes, constructors, methods, member variables, parameters and local variables. This information is stored in the "name=value" pair of annotation.
- In Java se, annotations are used for simple purposes, such as marking outdated functions, ignoring warnings, etc. Annotations play a more important role in Java EE / Android, such as configuring any aspect of the application, replacing the cumbersome code and XML configuration left over from the old version of Java EE.
- Future development models are annotation based, JPA is annotation based, spring 2 5 the above are based on annotations, hibernate 3 X is also based on annotations in the future. Now some of struts 2 is also based on annotations. Annotation is a trend. To a certain extent, it can be said: Framework = annotation + reflection + design pattern.
2.2. Use examples of Annotation
- When using Annotation, add the @ symbol in front of it, and use the Annotation as a modifier. Used to decorate the program elements it supports
- Example 1: generate document related annotations
- @The author indicates the author who develops this kind of module, which can be used and divided among multiple authors
- @Version indicates the version of this type of module
- @see reference turn, that is, related topics
- @Which version of since was added
- @param describes a parameter in the method. If there is no parameter, it cannot be written
- @Return describes the return value of the method. If the return value type of the method is void, it cannot be written
- @Exception describes the exceptions that may be thrown by the method. If the method does not explicitly throw an exception with throws, it cannot be written to it
- @param @return and @ exception are only used for methods.
- @Format requirements for param: @ param parameter name parameter type parameter description
- @Return format requirements: @ return return return value type return value description
- @Format requirements for exception: @ exception exception exception type exception description
- @param and @ exception can be multiple in parallel
- Example 2: format checking at compile time (three basic annotations built into JDK)
- @Override: restrict overriding parent class methods. This annotation can only be used for methods
- @Deprecated: used to indicate that the modified element (class, method, etc.) is obsolete. Usually because the modified structure is dangerous or there is a better choice
- @SuppressWarnings: suppresses compiler warnings
- Example 3: track code dependencies and implement the function of replacing configuration files
- Servlet3.0 provides annotations so that they are no longer needed on the web Deploy servlets in XML files.
- Management of "transaction" in spring framework
import java.util.ArrayList; import java.util.Date; /** * Use of annotations * * 1. Understanding Annotation: * ① jdk 5.0 New features * * ② Annotation In fact, they are special tags in the code. These tags can be read and processed during compilation, class loading and runtime. By using Annotation, * Programmers can embed some supplementary information in the source file without changing the original logic. * * ③In Java se, annotations are used for simple purposes, such as marking outdated functions, ignoring warnings, etc. In Java EE / Android * Annotations play a more important role, such as configuring any aspect of the application, instead of the cumbersome legacy of the older versions of Java EE * Code and XML configuration, etc. * * 2. Annocation Use examples of * Example 1: generate document related annotations * Example 2: format checking at compile time (three basic annotations built into JDK) * @Override: The annotation can only be used for overriding parent class methods * @Deprecated: Used to indicate that the modified element (class, method, etc.) is obsolete. Usually because the modified structure is dangerous or there is a better choice * @SuppressWarnings: Suppress compiler warnings * * Example 3: track code dependencies and implement the function of replacing configuration files */ public class AnnotationTest { public static void main(String[] args) { Person p = new Student(); p.walk(); Date date = new Date(2020, 10, 11); System.out.println(date); @SuppressWarnings("unused") int num = 10; // System.out.println(num); @SuppressWarnings({ "unused", "rawtypes" }) ArrayList list = new ArrayList(); } } class Person{ private String name; private int age; public Person() { super(); } public Person(String name, int age) { this.name = name; this.age = age; } public void walk(){ System.out.println("Learning"); } public void eat(){ System.out.println("Fishing"); } } interface Info{ void show(); } class Student extends Person implements Info{ @Override public void walk() { System.out.println("Spray away"); } @Override public void show() { } }
2.3. How to customize annotations
- Define a new Annotation type using the @ interface keyword
- Custom annotations automatically inherit Java lang.annotation. Annotation interface
- The member variables of Annotation are declared as parameterless methods in the Annotation definition. Its method name and return value define the name and type of the member. We call it configuration parameters. The type can only be an array of eight basic data types, String type, Class type, enum type, Annotation type and all the above types.
- You can specify the initial value for the Annotation's member variable when it is defined. You can use the default keyword to specify the initial value of the member variable
- If there is only one parameter member, it is recommended to use the parameter name value
- If the defined annotation contains configuration parameters, the parameter value must be specified when using, unless it has a default value. The format is "parameter name = parameter value". If there is only one parameter member and the name is value, "value =" can be omitted
- Annotations without member definitions are called tags; Annotations that contain member variables are called metadata annotations
- Note: the user-defined annotation must be accompanied by the annotation information processing process to be meaningful.
public @interface MyAnnotation { String value(); } /** * Use of annotations * * 3.How to customize annotations: refer to the @ SuppressWarnings definition * ① Annotation declared as: @ interface * ② Internally defined members, usually represented by value * ③ You can specify the default value of the member, which is defined by default * ④ If the custom annotation has no members, it indicates that it is an identification function. * * If the annotation has members, you need to specify the value of the members when using the annotation. * Custom annotations must be accompanied by an annotated information processing process (using reflection) to make sense. * The user-defined annotation will indicate two meta annotations: Retention and Target * */ @MyAnnotation(value = "hello")
2.4 use of four basic meta annotations in jdk 1
-
The meta Annotation of JDK is used to modify other Annotation definitions
-
JDK5.0 provides four standard meta annotation types:
- `Retention
- Target
- Documented
- Inherited
Understanding of metadata: String name = "MyBlog";
- @Retention: can only be used to decorate an Annotation definition to specify the life cycle of the Annotation, @ retention contains a member variable of RetentionPolicy type. When using @ retention, you must specify a value for the value member variable:
- RetentionPolicy.SOURCE: valid in the source file (i.e. source file retention). The compiler directly discards the comments of this strategy
- RetentionPolicy.CLASS: it is valid in the class file (i.e. class retention). When running Java programs, the JVM will not retain annotations. This is the default
- RetentionPolicy.RUNTIME: valid at run time (i.e. reserved at run time). When running Java programs, the JVM will retain comments. The program can get the comment through reflection.
import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @Retention(RetentionPolicy.SOURCE) public @interface MyAnnotation { String value(); } /** * Use of annotations * * 4.jdk Four meta annotations provided * Meta annotation: an annotation that explains existing annotations * Retention:Specifies the lifecycle of the decorated Annotation: SOURCE\CLASS (default behavior) \ RUNTIME * Only annotations declared as RUNTIME lifecycles can be obtained through reflection. * Target: * Documented: * Inherited: * */ public class AnnotationTest { public static void main(String[] args) { } } @MyAnnotation(value = "hello") class Person{ private String name; private int age; public Person() { super(); } @MyAnnotation(value = "jack") public Person(String name, int age) { this.name = name; this.age = age; } public void walk(){ System.out.println("Learning"); } public void eat(){ System.out.println("Fishing"); } }
2.5 use of four basic meta annotations in jdk 2
- @Target: used to modify the Annotation definition. It is used to specify which program elements can be modified by the modified Annotation@ Target also contains a member variable named value.
- @Documented: used to specify that the Annotation class modified by the meta Annotation will be extracted into a document by the javadoc tool. By default, javadoc does not include annotations.
- Annotations defined as Documented must have the Retention value set to RUNTIME.
- @Inherited: the Annotation modified by it will be inherited. If a class uses an Annotation modified by @ inherited, its subclasses will automatically have the Annotation.
- For example, if the custom annotation marked with @ Inherited annotation is marked at the class level, the subclass can inherit the annotation at the parent class level
- In practical application, it is less used
import org.junit.Test; import java.lang.annotation.Annotation; import java.util.ArrayList; import java.util.Date; /** * Use of annotations * * 4.jdk Four meta annotations provided * Meta annotation: an annotation that explains existing annotations * Retention:Specifies the lifecycle of the decorated Annotation: SOURCE\CLASS (default behavior) \ RUNTIME * Only annotations declared as RUNTIME lifecycles can be obtained through reflection. * Target:Used to specify which program elements can be modified by the modified Annotation * *******The frequency of occurrence is low******* * Documented:Indicates that the modified annotation is retained when it is parsed by javadoc. * Inherited:The Annotation decorated by it will be inherited. * * 5.Obtain annotation information through reflection - explain the system when reflecting the content */ public class AnnotationTest { public static void main(String[] args) { } @Test public void testGetAnnotation(){ Class clazz = Student.class; Annotation[] annotations = clazz.getAnnotations(); for(int i = 0;i < annotations.length;i++){ System.out.println(annotations[i]); } } } @MyAnnotation(value = "hello") class Person{ private String name; private int age; public Person() { super(); } @MyAnnotation public Person(String name, int age) { this.name = name; this.age = age; } @MyAnnotation public void walk(){ System.out.println("Learning"); } public void eat(){ System.out.println("Fishing"); } } @Inherited @Retention(RetentionPolicy.RUNTIME) @Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE,TYPE_PARAMETER,TYPE_USE}) public @interface MyAnnotation { String value() default "book"; }
2.6. Obtain annotation information by reflection
JDK 5.0 in Java The AnnotatedElement interface is added under lang.reflect package, which represents the program elements that can accept annotations in the program
When an Annotation type is defined as runtime Annotation, the Annotation will be visible at runtime. When the class file is loaded, the Annotation saved in the class file will be read by the virtual machine
The program can call the following methods of the AnnotatedElement object to access the Annotation information
2.7. jdk8 new feature: repeatable annotation
Java 8 provides two improvements to annotation processing: repeatable annotations and annotations that can be used for types. In addition, reflection has been enhanced, and the names of method parameters can be obtained in Java 8. This simplifies annotation on method parameters.
import java.lang.annotation.Annotation; /** * Use of annotations * * 6.jdk 8 New features of annotations in: repeatable annotations, type annotations * * 6.1 Repeatable annotation: ① declare @ repeatable on MyAnnotation, and the member value is myannotations class * ② MyAnnotation Meta annotations such as Target and Retention are the same as MyAnnotations. * * * @author subei * @create 2020-05-11 11:19 */ public class AnnotationTest { public static void main(String[] args) { } } @MyAnnotation(value = "hi") @MyAnnotation(value = "abc") //Before jdk 8: //@MyAnnotations({@MyAnnotation(value="hi"),@MyAnnotation(value="hi")})
2.8. jdk8 new feature: type annotation
- JDK1. After 8, there are two more ElementType enumeration values for the parameter type of the meta annotation @ Target: TYPE_PARAMETER,TYPE_USE.
- Before Java 8, annotations could only be used where they were declared. From Java 8, annotations could be applied anywhere.
- ElementType.TYPE_PARAMETER indicates that the annotation can be written in the declaration statement of type variables (such as generic declaration).
- ElementType.TYPE_USE indicates that the annotation can be written in any statement using the type.
import java.util.ArrayList; /** * Use of annotations * * 6.jdk 8 New features of annotations in: repeatable annotations, type annotations * * 6.1 Repeatable annotation: ① declare @ repeatable on MyAnnotation, and the member value is myannotations class * ② MyAnnotation Meta annotations such as Target and Retention are the same as MyAnnotations. * * 6.2 Type notes: * ElementType.TYPE_PARAMETER Indicates that the annotation can be written in the declaration statement of type variables (e.g. generic declaration). * ElementType.TYPE_USE Indicates that the annotation can be written in any statement using the type. * */ public class AnnotationTest { } class Generic<@MyAnnotation T>{ public void show() throws @MyAnnotation RuntimeException{ ArrayList<@MyAnnotation String> list = new ArrayList<>(); int num = (@MyAnnotation int) 10L; } }
MyAnnotation class
import java.lang.annotation.*; import static java.lang.annotation.ElementType.*; @Retention(RetentionPolicy.RUNTIME) @Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE,TYPE_PARAMETER,TYPE_USE}) public @interface MyAnnotation { String value() default "hello"; }