Enumeration classes and annotations

Posted by pohopo on Fri, 31 Dec 2021 19:08:29 +0100

1. Use of 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 use of enumeration class: getting started

  • Class has only a limited number of objects, which is uncertain. Examples are as follows:
     week: 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: creation, ready, running, blocking and death
  • 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.

Enumeration class properties

  • The properties of a class object should not be allowed to be changed, so it should be decorated with private final
  • 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.2 user defined enumeration class

  1. Privatize the constructor of the class to ensure that its objects 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
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");
}

1.3 using enum to define enumeration classes

  • instructions
     the enum class defined by enum inherits Java by default Lang. enum class, so it can no longer be used
    Inherit other classes
     the constructor of enumeration class can only use the private permission modifier
     all instances of enumeration class must be explicitly listed in enumeration class (, separated; end). The public static final modifier will be automatically added to the listed instances
     enumeration class object must be declared on the first line of 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");
	private final String seasonName;
	private final 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 object array of enumeration type. This method can easily traverse all enumeration values.
     valueOf(String str): a string can be converted into a corresponding enumeration 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

1.5 enumeration classes for implementing interfaces

  • 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:
 overview of annotation
 common Annotation examples
 user defined Annotation
 meta annotation in JDK
 obtain annotation information by reflection (involved in reflection)
 new features of annotations in JDK 8

2.1 annotation overview

 starting from 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 during compilation, class loading and runtime, and perform corresponding processing. 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. These information is saved 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 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
    @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
    among
    @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
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 check during compilation (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: suppress compiler warnings
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
     Servlet3.0 provides annotations so that they are no longer needed on the web Deploy servlets in XML files
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException { }
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
		doGet(request, response);
} }


<servlet>
	<servlet-name>LoginServlet</servlet-name>
	<servletclass>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 and use the @ interface keyword
 custom annotations automatically inherit Java lang.annotation. Annotation interface
 the member variables of Annotation are declared in the form of parameterless method 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 when defining the member variable of Annotation, and the default keyword can be used to specify the initial value of 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; Annotation s 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.

@MyAnnotation(value="Western industry and Commerce")
public class MyAnnotationTest {
	public static void main(String[] args) {
		Class clazz = MyAnnotationTest.class;
		Annotation a = clazz.getAnnotation(MyAnnotation.class);
		MyAnnotation m = (MyAnnotation) a;
		String info = m.value();
		System.out.println(info);
	}
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@interface MyAnnotation{
	String value() default "xigongshang";
}