Java enumeration classes and annotations -- an article to understand enumeration classes and annotations

Posted by freeloader on Wed, 02 Feb 2022 16:43:21 +0100

1, Enumeration class

There are only a limited number of objects in a class, which is uncertain We call this class enumeration class

explain:

  1. There are only a limited number of objects of class, which is uncertain. For example:
    • 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: Nonpayment, Paid, Delivered, Return, Checked and Fulfilled
    • Thread status: create, ready, running, blocking, dead
  2. Enumeration classes are strongly recommended when you need to define a set of constants.
  3. If the enumeration has only one object, it can be used as an implementation of singleton mode.

Implementation of enumeration class:

  1. JDK1. You need to customize the enumeration class before 5.
  2. The enum keyword added in JDK 1.5 is used to define enumeration classes.

Properties of enumeration class:

  1. The properties of enumeration class objects should not be allowed to be changed, so they should be decorated with private final.
  2. The private final decorated attribute of the enumeration class should be assigned a value in the constructor.
  3. If the enumeration class explicitly defines a constructor with parameters, the corresponding incoming parameters must also be used when listing the enumeration values.

① Custom enumeration class

Write a custom class to implement the custom enumeration class.

Implementation of custom 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.

Demo:

package com.broky.EnumClass;

/**
 * Custom enumeration class
 *
 * @author 13roky
 * @date 2021-05-13 17:16
 */
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
    // final cannot use initialization assignment, but can manually and explicitly assign, constructor assignment and code block assignment
    // Current assignment and code block assignment will result in the same properties when creating different objects of the current class
    // Constructor assignment can set properties when instantiating
    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
    public static Season SPRING = new Season("spring","in the warm spring , flowers are coming out with a rush");
    public static Season SUMMER = new Season("summer","Summer heat");
    public static Season AUTUMN = new Season("autumn","fresh autumn weather");
    public static Season WINTER = new Season("winter","a world of ice and snow");

    // 4. Other claims 1: get the properties of enumeration objects
    public String getSeasonName() {
        return seasonName;
    }

    public String getSeasonDesc() {
        return seasonDesc;
    }

    // 5. Other claims 2: toString ()
    @Override
    public String toString() {
        return "Season{" + "seasonName='" + seasonName + '\'' + ", seasonDesc='" + seasonDesc + '\'' + '}';
    }
}

② enum keyword defines an enumeration class

By using enum keyword and some simple rules, it is more convenient to create enumeration classes

explain:

  1. Enum enumeration class inherits Java Lang. enum class, so if toString is not rewritten, Java. Enum is used ToString in lang.enum will not output the memory address, but will print the object name

Implementation of enum enumeration class:

  1. Use enum to declare the class as an enumeration class.

  2. At the beginning of the enumeration class, first define the objects required in the enumeration class.

    • Enumeration class simplifies the object of instantiating enumeration class

      Instantiation can be completed only by using the object name (parameter ·····), such as:

      Spring ("spring", "spring flowers bloom"), WINTER("winter", "ice and snow");

      Multiple objects are separated by "," and the last one is separated by " ending

      If there are no attributes, you can remove the brackets, such as:

      PRING, WINTER;

  3. The rest of the rules are the same as the custom enumeration class.

Demo:

package com.broky.EnumClass;

/**
 * @author 13roky
 * @date 2021-05-13 18:32
 */
public class SeasonTest1 {
    public static void main(String[] args) {
        Season1 spring = Season1.SPRING;
        System.out.println(spring);
        System.out.println(Season1.class.getSuperclass());
    }
}

enum Season1 {
    // 1. Provide the object of the current enumeration class. Multiple objects are separated by "," and the end object is separated by " end
    SPRING("spring", "in the warm spring , flowers are coming out with a rush"), 
    SUMMER("summer", "Summer heat"), 
    AUTUMN("autumn", "fresh autumn weather"), 
    WINTER("winter", "a world of ice and snow");

    // 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 claims 1: get the properties of enumeration objects
    public String getSeasonName() {
        return seasonName;
    }

    public String getSeasonDesc() {
        return seasonDesc;
    }

    // 5. Other demands 2: toString ()
    // When toString is not rewritten, if enum class inherits Object class, toString of Object should be used to print the address value
    // However, through practice, it is known that the printed address value is not the address value, which is determined by Season1 class. Getsuperclass () knows that its parent class is Java lang.Enum

    //    @Override
    //    public String toString() {
    //        return "Season{" + "seasonName='" + seasonName + '\'' + ", seasonDesc='" + seasonDesc + '\'' + '}';
    //    }
}

③ enum enumeration class method

  • **values(): * * returns an array of objects of enumeration type. This method can easily traverse all enumerated values.
  • **valueOf(String str): * * you can convert a string into a corresponding enumeration object. The string is required to be the "name" of the 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.

Demo: (enumeration class uses the enumeration class Season1 of the above code)

package com.broky.EnumClass;

import java.util.Arrays;

/**
 * @author 13roky
 * @date 2021-05-13 18:32
 */
public class SeasonTest1 {
    public static void main(String[] args) {
        Season1 spring = Season1.SPRING;
        System.out.println(spring);
        System.out.println(Season1.class.getSuperclass());

        System.out.println("************************************");
        // values() method: returns an array of objects of enumeration type. This method can easily traverse all enumerated values.
        Season1[] values = Season1.values();
        System.out.println(Arrays.toString(values));

        Thread.State[] values1 = Thread.State.values();
        System.out.println(Arrays.toString(values1));

        System.out.println("************************************");
        // valueOf(String str): returns the object whose object name is objName in the enumeration class.
        // You can convert a string into a corresponding enumeration class object.
        // The string is required to be the "name" of the enumeration class object. If not, there will be a runtime exception: IllegalArgumentException.
        Season1 winter1= Season1.valueOf("WINTER");
        System.out.println(winter1);

        System.out.println("************************************");

        // toString(): returns the name of the object constant of the current enumeration class.
        System.out.println(winter1.toString());
    }
}

④ enum enumeration class implementation interface

enum enumeration class can implement the interface and rewrite the methods in the interface like normal class

However, enum enumeration class also has its unique method to implement the interface. Each object in the interface class can override the method to implement the interface alone

The method of implementing interface specific to enum object:

  • Object name (constructor parameter) {method to be overridden}, such as:
    AUTUMN("autumn", "fresh autumn weather"){
        @Override
        public void show() {
            System.out.println("fresh autumn weather");
        }
    },
    WINTER("winter", "a world of ice and snow"){
        @Override
        public void show() {
            System.out.println("Winter has come");
        }
    };

Demo:

package com.broky.EnumClass;

import org.junit.jupiter.api.Test;

import java.util.Arrays;

/**
 * @author 13roky
 * @date 2021-05-13 18:32
 */
public class SeasonTest1 {
    @Test
    public void test(){
        Season1 spring = Season1.SPRING;
        spring.show();
        Season1.SUMMER.show();
    }
}

interface info{
    void show();
}

enum Season1 implements info{
    // enum's unique method of implementing interface
    // 1. Provide the object of the current enumeration class. Multiple objects are separated by "," and the end object is separated by " end
    SPRING("spring", "in the warm spring , flowers are coming out with a rush"){
        @Override
        public void show() {
            System.out.println("Where is spring");
        }
    },
    SUMMER("summer", "Summer heat"){
        @Override
        public void show() {
            System.out.println("summer");
        }
    },
    AUTUMN("autumn", "fresh autumn weather"){
        @Override
        public void show() {
            System.out.println("fresh autumn weather");
        }
    },
    WINTER("winter", "a world of ice and snow"){
        @Override
        public void show() {
            System.out.println("Winter has come");
        }
    };

    // 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 claims 1: get the properties of enumeration objects
    public String getSeasonName() {
        return seasonName;
    }

    public String getSeasonDesc() {
        return seasonDesc;
    }

    @Override
    public void show() {
        System.out.println("This is a season");
    }

}

2, 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 as a modifier to modify the declaration of packages, classes, constructors, methods, member variables, parameters and local variables. This 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 will also be based on annotation in the future. Now some of struts 2 is also based on annotation. Annotation is a trend. To a certain extent, it can be said: Framework = annotation + reflection + design pattern.

  • 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

① Generate document related annotations

Usage:

  • @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 is a description of 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

explain:

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

Demo:

package com.broky.EnumClass;

/**
 * @author 13roky
 * @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;
    }
}

② Annotations are format checked at compile time

During compilation, the method at the annotation will be forced to check whether it conforms to the annotation. If not, an error will be reported

There are 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, attribute, etc.) is outdated. It is usually because the modified structure is dangerous or there is a better choice
  • @SuppressWarnings: suppress compiler warnings and eliminate warnings of a piece of code in the compiler

Demo:

package com.broky.EnumClass;

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()";
    }
}

③ Annotation tracks the dependency of code and realizes the function of replacing configuration file

  • Servlet3.0 provides annotation, so that it is no longer needed on the web Deploy servlets in XML files.
import java.io.IOException;

@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><servlet-class>com.servlet.LoginServlet</servlet-class></servlet><servlet-mapping><servlet-name>LoginServlet</servlet-name><url-pattern>/login</url-pattern></servlet-mapping>
  • Management of "transaction" in spring framework
 @Transactional(propagation = Propagation.REQUIRES_NEW, isolation = Isolation.READ_COMMITTED, readOnly = false, timeout = 3) public void buyBook(String username,String isbn){        //1. Unit price of query book int price = bookshopdao findBookPriceByIsbn(isbn);        // 2. Update inventory bookshopdao updateBookStock(isbn);        // 3. Update the user's balance bookshopdao updateUserAccount(username,price);        }
<!-- Configure transaction properties --><tx:advice transaction-manager="dataSourceTransactionManager" id="txAdvice"><tx:attributes><!-- Configure the transaction properties used by each method --><tx:method name="buyBook" propagation="REQUIRES_NEW"isolation="READ_COMMITTED" read-only="false" timeout="3" /></tx:attributes></tx:advice>

④ Custom annotation

explain:

  • 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 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 member variable of Annotation when defining it. 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 containing member variables are called metadata annotations. Note: Custom annotations must be accompanied by Annotation information processing processes to be meaningful.

Note: the user-defined annotation must be accompanied by the annotation information processing process to be meaningful. (implemented using reflection)

Demo:

package com.broky.EnumClass;/** * @author 13roky * @date 2021-05-14 8:36 */public @interface MyAnnotation {    String value() default "test";}package com.broky.EnumClass;/** * @author 13roky * @date 2021-05-14 8:16 */public class AnnotationTest {    @MyAnnotation()    void test(){            }}

⑤ Four meta annotations provided by jdk

explain:

  • The meta Annotation of JDK is used to modify other Annotation definitions
  • JDK5.0 provides four standard meta annotation types:
    • Retention
    • Target
    • Documented
    • Inherited

Meta annotation Description:

  • @Retention: can only be used to decorate an Annotation definition and 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 (default): * * 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 runtime (i.e. reserved at runtime). When running Java programs, the JVM will retain comments. The program can get the comment through reflection

      Only annotations declared as RUNTIME lifecycles can be obtained 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.

[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (IMG yxohok5a-1622595056140)( https://i.vgy.me/JvS9L6.png )]

@Target({FIELD,METHOD,TYPE})@Retention(RetentionPolicy.SOURCE)@interface MyAnnotation1{ }
  • @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

Understanding of metadata:

String name ="13roky"

In this data, 13roky is the most important. Both String and name modify it. Then String and name can be called metadata: data used to modify data

⑥ New feature of JKD8: repeatable annotation

Implementation of repeated annotation before JDK8:

Before JDK8, if you want to add multiple identical annotations at the same location, you need to use an array to add them.

package com.broky.EnumClass;import java.lang.annotation.*;import static java.lang.annotation.ElementType.*;/** * @author 13roky * @date 2021-05-14 8:36 */@Retention(RetentionPolicy.SOURCE)@Target({FIELD, METHOD})public @interface MyAnnotation {    String[] value();}
package com.broky.EnumClass;/** * @author 13roky * @date 2021-05-14 8:16 */public class AnnotationTest {    @MyAnnotation({"123","456"})    void test(){    }}

New feature of JKD8: repeatable annotation:

  • Declare @ Repeatable on MyAnnotation, and the member value is annotations class
  • The target, inherited and Retention of MyAnnotation are the same as those of Annotations.

Demo:

package com.broky.EnumClass;/** * @author 13roky * @date 2021-05-14 8:16 */public class AnnotationTest {    @MyAnnotation()    @MyAnnotation()    void test(){    }}
package com.broky.EnumClass;import java.lang.annotation.*;import static java.lang.annotation.ElementType.*;/** * @author 13roky * @date 2021-05-14 8:36 */@Repeatable(MyAnnotations.class)@Retention(RetentionPolicy.SOURCE)@Target({FIELD, METHOD})public @interface MyAnnotation {    String value() default "test";}
package com.broky.EnumClass;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;import static java.lang.annotation.ElementType.FIELD;import static java.lang.annotation.ElementType.METHOD;/** * @author 13roky * @date 2021-05-14 9:43 */@Retention(RetentionPolicy.SOURCE)@Target({FIELD, METHOD})public @interface MyAnnotations {    MyAnnotation[] value();}

⑦ New feature of JDK8: type annotation

It can be understood that the type annotation is the meta annotation @ Target, which adds two parameter types

TYPE_PARAMETER, TYPE_USE

explain:

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

Demo:

// Add the parameter type in the @ Target of the custom annotation_ Parameterclass generic < @ myannotation T > {/ / add the parameter type_use public void show() throws @ myannotation runtimeException {ArrayList < @ myannotation string > List = new ArrayList < > (); int num = (@ myannotation int) 10L;}}
package com.broky.EnumClass;import java.lang.annotation.*;import static java.lang.annotation.ElementType.*;/** * @author 13roky * @date 2021-05-14 8:36 */@Repeatable(MyAnnotations.class)@Retention(RetentionPolicy.SOURCE)@Target({FIELD, METHOD, TYPE_PARAMETER,TYPE_USE})public @interface MyAnnotation {    String value() default "test";}

Topics: Java