Enumeration classes and annotations

1. Enumeration class

Main contents:

  • How to customize enumeration classes
  • How to define enumeration classes using the keyword enum
  • Main methods of Enum class
  • Enumeration class that implements the interface

1.1 INTRODUCTION

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 (silver)
    Bank card), creditcard
  • Employment status: Busy, Free, Vocation, Dimission
  • Order status: unpaid, Paid, Delivered
    Return, Checked, filled
  • Thread status: create, ready, running, blocking, dead

Enumeration classes are strongly recommended when you need to define a set of constants

1.2 use of enumeration class

Implementation of enumeration class

  • You need to customize the enumeration class before JDK1.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.

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

1.3. User defined enumeration class

1. Privatize the constructor of the class to ensure that its object cannot be created outside the class
2. Create an instance of the enumeration class inside the class. Declared as: public static final
3. If the object has an instance variable, it should be declared as private final and initialized in the constructor

public class Season {
    private final String SEASONNAME;//Name of season
    private final String SEASONDESC;//Description of seasons
    private Season(String seasonName,String seasonDesc){
        this.SEASONNAME=seasonName;
        this.SEASONDESC=seasonDesc;
    }
    public static final Season SPRING = new Season("spring", "in the warm spring , flowers are coming out with a rush");
    public static final Season SUMMER = new Season("summer", "Summer heat");
    public static final Season AUTUMN = new Season("autumn", "fresh autumn weather");
    public static final Season WINTER = new Season("winter", "snow gleams white");
}

instructions
Enum classes defined with enum inherit the java.lang.Enum class by default, so they cannot 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.

public enum SeasonEnum {
    SPRING("spring","Spring breeze and green river south bank"),
    SUMMER("summer","The lotus in the sun is very red"),
    AUTUMN("autumn","The autumn river shares a scenic hue with the vast sky"),
    WINTER("winter","The window contains thousands of autumn snow in Xiling");
    String seasonName;
    String seasonDesc;
    private SeasonEnum(String seasonName,String seasonDesc){
        this.seasonName=seasonName;
        this.seasonDesc=seasonDesc;
    }

    public String getSeasonName() {
        return seasonName;
    }
    
    public String getSeasonDesc() {
        return seasonDesc;
    }

}

1.4 main methods of Enum class

Main methods of Enum class:

  • values() method: returns an array of objects of enumeration type. This method can easily traverse all the
    Enumeration value.
  • 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

Like ordinary Java classes, enumeration classes can implement one or more interfaces
If each enumeration value presents the same behavior when calling the implemented interface method, it is only necessary to implement the method uniformly.
If you need each enumeration value to show different behavior when calling the implemented interface method, you can let each enumeration value implement the method separately

2. Annotation

Main contents:

  • Annotation overview
  • Common Annotation examples
  • Custom Annotation
  • Meta annotation in JDK
  • Use reflection to obtain annotation information (involved in the reflection part)
  • New features of annotations in JDK 8

2.1 overview of annotation

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 and above are annotation based. Hibernate 3. X will also be annotation based. Now some of struts 2 is also annotation based. Annotation is a trend. To a certain extent, it can be said: Framework = annotation + reflection + design mode.

2.2 common Annotation examples

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

@author Indicate the author who developed this type of module, which can be used among multiple authors,division
@version Indicate the version of such modules
@see Reference turn, that is, related topics
@since Which version was added from
@param The description of a parameter in the method. If there is no parameter, it cannot be written
@return Description of the return value of the method. If the return value type of the method is void You can't write
@exception Describe the exceptions that may be thrown by the method. If the method is useless throws Exceptions thrown explicitly cannot be written

among

@param @return and @exception All three tags are for methods only.
@param Format requirements:@param Parameter name parameter type parameter description
@return Format requirements:@return Return value type return value description
@exception Format requirements:@exception Exception type exception description
@param and@exception Multiple can be juxtaposed
package com.annotation.javadoc;
	/**
	* @author shkstart
	* @version 1.0
	* @see Math.java
	*/
public class JavadocTest {
	/**
	* The main method of the program, the entry of the program
	* @param args String[] Command line parameters
	*/
	public static void main(String[] args) {
	}
	/**
	* Method for calculating circular area
	* @param radius double Radius value
	* @return double Area of circle
	*/
	public static double getArea(double radius){
		return Math.PI * radius * radius;
	}
}

Example 2: format checking at compile time (three basic annotations built into JDK)

@Override: Qualified override parent method, This annotation can only be used for methods
@Deprecated: Used to represent the modified element(class, Methods, etc)Obsolete. Usually because
 The modified structure is dangerous or there is a better choice
@SuppressWarnings: Suppress compiler warnings

Common Annotation examples

package com.annotation.javadoc;
public class AnnotationTest{
public static void main(String[] args) {
	@SuppressWarnings("unused")
	int a = 10;
}
	@Deprecated
	public void print(){
	System.out.println("Outdated methods");
}
	@Override
	public String toString() {
	return "Rewritten toString method()";
	}
}

Example 3: track code dependencies and implement the function of replacing configuration files

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throwsServletException, IOException { }
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throwsServletException, IOException {
	doGet(request, response);
	}
}
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>com.servlet.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>

2.3. User defined Annotation

Define a new Annotation type using the @ interface keyword
Custom annotations automatically inherit the 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 and the initial value of the member variable of Annotation when defining its member variable
Values can use the default keyword

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
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.

2.4 meta annotation in JDK

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:
@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 policy
  • RetentionPolicy.CLASS: valid in the class file (i.e. class reservation). 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.
public enum RetentionPolicy{
	SOURCE,
	CLASS,
	RUNTIME
}
@Retention(RetentionPolicy.SOURCE)
@interface MyAnnotation1{ }

@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation2{ }

@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.

Value ElementTypeexplain
TYPEUsed to describe classes, interfaces (including annotation types) or enum declarations
FIELDUsed to describe a domain (property)
METHODUser description method
PARAMETERUsed to describe parameters
CONSTRUCTORUsed to describe constructors
LOCAL_VARIABLEUsed to describe local variables
ANNOTATION_TYPEApply to an annotation type
PACKAGEUsed to describe the package
TYPE_PARAMETERIndicates that the annotation can be used in the declaration statement of user-defined type parameters (the user-defined type of parameters can be javaBean or enumeration, etc.).
TYPE_USEIndicates that the annotation can be used in any statement using the type.

@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

2.5. Obtain annotation information by reflection

JDK 5.0 adds an AnnotatedElement interface under the java.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 virtual
Machine reading

The program can call the following methods of the AnnotatedElement object to access the Annotation information

2.6 new features of annotations in JDK8

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.

Examples of repeatable annotations:

Type notes:
After JDK1.8, there are two more ElementType enumeration values for the parameter type of meta annotation @ Target:
TYPE_PARAMETER,TYPE_USE.

Before Java 8, annotations can only be used where they are declared. From Java 8, annotations can 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.

public class TestTypeDefine<@TypeDefine() U> {
	private U u;
	public <@TypeDefine() T> void test(T t){
	}
	}
	@Target({ElementType.TYPE_PARAMETER})
	@interface TypeDefine{
}
@MyAnnotation
public class AnnotationTest<U> {
	@MyAnnotation
	private String name;
	public static void main(String[] args) {
		AnnotationTest<@MyAnnotation String> t = null;
		int a = (@MyAnnotation int) 2L;
		@MyAnnotation
		int b = 10;
	}
	public static <@MyAnnotation T> void method(T t) {
	}
	public static void test(@MyAnnotation String arg) throws @MyAnnotation 	Exception {
		}
	}
	@Target(ElementType.TYPE_USE)
	@interface MyAnnotation {
	}

Tags: Java

Posted on Thu, 16 Sep 2021 13:17:40 -0400 by Splynx