This is the 20th day of my participation in the August Text Challenge.More challenges in August

1. Use of enumerated classes

1.1. Understanding enumeration classes

  • Class has a finite number of objects, deterministic. Examples are as follows:
    • Week: Monday,… Sunday, Sunday
    • Gender: Man, Woman
    • Season: Spring festival… Winter (Winter)
    • Payment methods: Cash, WeChatPay, Alipay, BankCard, CreditCard
    • Working status: Busy, Free, Vocation, Dimission
    • This is a big pity. The order status is Fulfilled: Nonpayment, Paid, Delivered, Return, Checked, and Fulfilled.
    • Thread states: created, ready, running, blocked, dead
  • Enumerated classes are strongly recommended when you need to define a set of constants
  • An implementation of an enumerated class
    • Before JDK1.5, you needed to customize enumerated classes
    • The enum keyword was added in JDK 1.5 to define enumerated classes
  • If the enumeration has only one object, it can be implemented as a singleton pattern.

1.2. Custom enumerated classes

Enumerates the properties of a class

  • The properties of an enumerated class object should not be allowed to be modified, so it should be usedprivate finalmodified
  • Use of enumeration classesprivate finalThe modified property should be assigned a value in the constructor
  • If an enumeration class explicitly defines a constructor with arguments, the enumeration values must also be listed with the corresponding passed arguments
/ * * * * 1. The use of a, enumerated type enumeration class understand: only a finite number of class object, certain. We call this class an enumerated class. * 2. Enumeration classes are strongly recommended when defining a set of constants. 3. Enumeration can be implemented as a singleton pattern if it has only one object. The enum keyword in JDK1.5 is used to define enum classes * */
public class SeasonTest {
    public static void main(String[] args) { Season spring = Season.SPRING; System.out.println(spring); }}// Custom enumerated classes
class Season{
    //1. Declare the private final property of the Season object
    private final String seasonName;
    private final String seasonDesc;

    //2. Privatize the class constructor and assign values to object attributes
    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"."The resurrection of all things.");
    public static final Season SUMMER = new Season("Summer"."The sun is burning.");
    public static final Season AUTUMN = new Season("Autumn"."Cool in autumn.");
    public static final Season WINTER = new Season("Winter"."All white with snow");

    //4. Other demands: Obtain the properties of the enumeration class object
    public String getSeasonName(a) {
        return seasonName;
    }

    public String getSeasonDesc(a) {
        return seasonDesc;
    }

    //4. Other appeal 1: Provide toString()
    @Override
    public String toString(a) {
        return "Season{" +
                "seasonName='" + seasonName + '\' ' +
                ", seasonDesc='" + seasonDesc + '\' ' +
                '} '; }}Copy the code

1.3. Define enumeration classes using the enum keyword

Directions for use

  • Enum classes defined with enum inherit from the java.lang. enum class by default and therefore cannot inherit from other classes
  • The constructor of an enumerated class can only use the private permission modifier
  • All instances of an enumerated class must be explicitly listed in the enumerated class (, separated; At the end). The public Static Final modifier is automatically added to the listed instances
  • An enumerated class object must be declared on the first line of the enumerated class

In JDK 1.5, it is possible to use objects of Enum classes defined by Enum as expressions in switch expressions, and case clauses can directly use the names of enumerated values without adding enumeration classes as qualifiers.

/** * Use the enum keyword to define enumeration classes * Description: Defined enumeration classes inherit from the java.lang. enum class */ by default
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()); }}// Enumerate classes using the enum keyword
enum Season1{
    //1. Provide the object of the current enumeration class, separated by ",", end object "; The end of the
    SPRING("Spring"."The resurrection of all things."),
    SUMMER("Summer"."The sun is burning."),
    AUTUMN("Autumn"."Cool in autumn."),
    WINTER("Winter"."All white with snow");

    //2. Declare the private final property of the Season object
    private final String seasonName;
    private final String seasonDesc;

    //3. Privatize the constructor of the class and assign values to the object attributes
    private Season1(String seasonName,String seasonDesc){
        this.seasonName = seasonName;
        this.seasonDesc = seasonDesc;
    }

    //4. Other demands: Obtain the properties of the enumeration class object
    public String getSeasonName(a) {
        return seasonName;
    }

    public String getSeasonDesc(a) {
        return seasonDesc;
    }

    //4. Other appeal 1: Provide toString()
// @Override
// public String toString() {
// return "Season{" +
// "seasonName='" + seasonName + '\'' +
// ", seasonDesc='" + seasonDesc + '\'' +
/ / '} ';
/ /}
}
Copy the code

1.4. Common methods in Enum classes

The main methods of the Enum class:

  • values()Method: Returns an array of objects of enumerated type. This method makes it easy to iterate over all enumerated values.
  • valueOf(String str): Converts a string to the corresponding enumeration object. The string must be the “name” of an enumeration class object. If not, there is a runtime exception: IllegalArgumentException.
  • toString(): Returns the name of the current enumeration class object constant
/** * Enumeration class defined with enum keyword * Description: the defined enumeration class inherits from java.lang.Enum class ** This method makes it easy to iterate over all enumerated values. * valueOf(String STR) : A String can be converted to the corresponding enumeration object. The string must be the "name" of an enumeration class object. If not, there is a runtime exception: IllegalArgumentException. * toString() : Returns the name of the current enumeration object constant */
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 enumerated 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 an object in the enumerated class whose object name is objName.
        Season1 winter = Season1.valueOf("WINTER");
        // If there is no enumeration object of objName, throw an exception: IllegalArgumentException
// Season1 winter = Season1.valueOf("WINTER1");System.out.println(winter); }}// Enumerate classes using the enum keyword
enum Season1{
    //1. Provide the object of the current enumeration class, separated by ",", end object "; The end of the
    SPRING("Spring"."The resurrection of all things."),
    SUMMER("Summer"."The sun is burning."),
    AUTUMN("Autumn"."Cool in autumn."),
    WINTER("Winter"."All white with snow");

    //2. Declare the private final property of the Season object
    private final String seasonName;
    private final String seasonDesc;

    //3. Privatize the constructor of the class and assign values to the object attributes
    private Season1(String seasonName,String seasonDesc){
        this.seasonName = seasonName;
        this.seasonDesc = seasonDesc;
    }

    //4. Other demands: Obtain the properties of the enumeration class object
    public String getSeasonName(a) {
        return seasonName;
    }

    public String getSeasonDesc(a) {
        return seasonDesc;
    }

    //4. Other appeal 1: Provide toString()
// @Override
// public String toString() {
// return "Season{" +
// "seasonName='" + seasonName + '\'' +
// ", seasonDesc='" + seasonDesc + '\'' +
/ / '} ';
/ /}
}
Copy the code

1.5. Implement the interface with an enumeration class defined by the enum keyword

/** * Use enum keyword to define enumeration classes * Note: The defined enumeration classes inherit from java.lang.Enum class by default ** Let the objects of the enumerated classes separately implement the abstract method */ in the interface
public class SeasonTest1 {
    public static void main(String[] args) {
        //values(): Returns an array of all enumerated 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 an object in the enumerated class whose object name is objName.
        Season1 winter = Season1.valueOf("WINTER"); winter.show(); }}interface Info{
    void show(a);
}

// Enumerate classes using the enum keyword
enum Season1 implements Info{
    //1. Provide the object of the current enumeration class, separated by ",", end object "; The end of the
    SPRING("Spring"."Spring Blossoms") {@Override
        public void show(a) {
            System.out.println("Everything begins again.");
        }
    },
    SUMMER("Summer"."Summer heat.") {@Override
        public void show(a) {
            System.out.println("Cicadas sound, sun in the sky.");
        }
    },
    AUTUMN("Autumn"."Crisp autumn air") {@Override
        public void show(a) {
            System.out.println("The sky is high, the air is clear, and the fragrance of gold laurel is fragrant.");
        }
    },
    WINTER("Winter"."Ice and Snow") {@Override
        public void show(a) {
            System.out.println("In the cold winter, water turns to ice."); }};//2. Declare the private final property of the Season object
    private final String seasonName;
    private final String seasonDesc;

    //3. Privatize the constructor of the class and assign values to the object attributes
    private Season1(String seasonName,String seasonDesc){
        this.seasonName = seasonName;
        this.seasonDesc = seasonDesc;
    }

    //4. Other demands: Obtain the properties of the enumeration class object
    public String getSeasonName(a) {
        return seasonName;
    }

    public String getSeasonDesc(a) {
        return seasonDesc;
    }

    //4. Other appeal 1: Provide toString()
// @Override
// public String toString() {
// return "Season{" +
// "seasonName='" + seasonName + '\'' +
// ", seasonDesc='" + seasonDesc + '\'' +
/ / '} ';
/ /}

// @Override
// public void show() {
// system.out. println(" This is a season." );
/ /}
}
Copy the code

2. Use of annotations

2.1 Understanding of annotations

  • Since JDK 5.0, Java has added support for MetaData, also known as annotations.
  • Annotations are just special marks in your code that can be read at compile time, class load time, run time, and do the processing. Using annotations, a programmer can embed supplementary information in a source file without changing the original logic. Code analysis tools, development tools, and deployment tools can be validated or deployed with this supplementary information.
  • Annotations can be used like modifiers to modify declarations of packages, classes, constructors, methods, member variables, parameters, and local variables. This information is stored in the “name=value” pair of annotations.
  • In JavaSE, annotations are used for simple purposes, such as marking outdated features, ignoring warnings, and so on. Annotations take on a more important role in JavaEE/Android, such as configuring any aspect of an application, replacing the cumbersome code and XML configuration left over from older versions of JavaEE.
  • JPA is annotation-based, Spring2.5 is annotation-based, hibernate3. x is annotation-based, and now Struts2 is partially annotation-based. Annotations are a trend, to some extent: Frame = annotation + reflection + design pattern.

2.2. Example of using annotations

  • When you use an Annotation, precede it with the @ sign and use the Annotation as a modifier. Used to modify the program elements it supports
  • Example 1: Generate annotations related to the document
    • @author indicates the author who developed the module, used between multiple authors, split
    • @version Indicates the version of this module
    • @see Reference turns, that is, related topics
    • @since which version was added from
    • @param Specifies an argument to a method that cannot be written without an argument
    • @return specifies the return value of a method, which cannot be written if the method return type is void
    • @exception Indicates the exceptions that the other method may throw. If the method does not throw exceptions explicitly throws throws, the method cannot be included
      • The @param@return and @exception tags are for methods only.
      • The format of @param must meet the following requirements: @param Parameter Name Parameter Type Parameter Description
      • The format of @return must meet the following requirements: @return Value Type Description of the returned value
      • The format of @exception is as follows: @exception Exception type Exception description
      • @param and @exception can be juxtaposed
  • Example 2: Format checking at compile time (three basic annotations built into the JDK)
    • Override: Qualified Override parent methods. This annotation can only be used for methods
    • Deprecated: Used to indicate that the modified element (class, method, etc.) is Deprecated. Usually because the structure being modified is dangerous or there is a better alternative
    • @SuppressWarnings: Suppress compiler warnings
  • Example 3: Track code dependencies and implement alternative profile functionality
    • Servlet3.0 provides annotations that eliminate the need to deploy servlets in web.xml files.
    • Management of “transactions” in the Spring framework
import java.util.ArrayList;
import java.util.Date;

/** ** ** * Annotation: * ① new features in JDK 5.0 ** ② Annotations are simply special marks in code that can be read and processed at compile, class load, or run time. Using annotations, * programmers can embed supplementary information in source files without changing the original logic. * * ③ In JavaSE, annotations are used for simple purposes, such as marking outdated features, ignoring warnings, etc. Annotations take on a more important role in JavaEE/Android *, such as configuring any aspect of an application, replacing the cumbersome * code and XML configuration left over from older versions of JavaEE. Example 1: Generating document-related annotations * Example 2: format checking at compile time (three basic annotations built into the JDK) *@OverrideThis annotation can only be used for method *@Deprecated: used to indicate that the element (class, method, etc.) being modified is obsolete. Usually because the structure being modified is dangerous or there is a better option *@SuppressWarnings: Suppress compiler warnings * * Example 3: Track code dependencies to implement alternative configuration file functionality */
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 = newArrayList(); }}class Person{
    private String name;
    private int age;

    public Person(a) {
        super(a); }public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
    public void walk(a){
        System.out.println("In the process of learning...");
    }
    public void eat(a){
        System.out.println("Among the fish..."); }}interface Info{
    void show(a);
}

class Student extends Person implements Info{

    @Override
    public void walk(a) {
        System.out.println("Troll away.");
    }

    @Override
    public void show(a) {}}Copy the code

2.3. How to customize annotations

  • Define a newThe Annotation classUse * *@interface* * keywords
  • Custom annotations automatically inherit **java.lang.annotation.Annotation* * interface
  • AnnotationThe member variable inAnnotationIs declared as a parameterless method in the definition. The method name and return value define the name and type of the member. We call this configuration parameter. The type can only be eight basic data types,String, Class, enum, Annotation, all of the above.
  • You can defineAnnotationTo specify an initial value for a member variable, use ** to specify an initial value for a member variabledefault* * keywords
  • If there is only one parameter member, you are advised to use the parameter name value
  • If the defined annotation contains configuration parameters, the parameter value must be specified when used unless it has a default value. The format is “Parameter name = Parameter Value”, if there is only one parameter member and the name isvalueCan be omitted.value=
  • No member definedAnnotationCalled a marker; Containing member variablesAnnotationIt’s called metadataAnnotation
  • Note: Custom annotations must be accompanied by annotation information processing to make sense.
public @interface MyAnnotation {

    String value(a);
}
3. How to customize annotations: reference@SuppressWarningsDefine * ① annotation declaration as:@interface* ② Internal definition of the member, usually using value for * ③ can specify the default value of the member, use default definition * ④ if the custom annotation does not have a member, it is an identifier. * * If the annotation has a member, the value of the member needs to be specified when using the annotation. * Custom annotations must be accompanied by the annotation's information processing flow (using reflection) to make sense. * Custom annotations that pass indicate two meta-annotations: Retention and Target * */

@MyAnnotation(value = "hello")
Copy the code

2.4 use of the four basic meta-annotations in the JDK 1

  • JDK meta-annotations are used to modify other Annotation definitions

  • JDK5.0 provides four standard meta-annotation types:

    • Retention
    • Target
    • Documented
    • Inherited

    String name = “MyBlog”;

  • @Retention: Is tention to only one Annotation definition, and is used to specify the life cycle of that Annotation. @Rentention is full of a member variable of type RetentionPolicy, for which a value must be specified when using @RentionPolicy:

    • RetentionPolicy.SOURCEThe compiler discards comments for this policy directly if it is valid in the source file
    • RetentionPolicy.CLASSAnnotations are valid in a class file (i.e. class reserved). The JVM does not retain annotations when running a Java program. This is the default value
    • RetentionPolicy.RUNTIME: valid at run time (i.e., runtime retention), annotations are retained by the JVM when running a Java program. 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(a);

}
* meta annotations: Annotations that explain existing annotations * Retention: Specifies the lifetime of the Annotation being modified: SOURCE\CLASS (default behavior) \RUNTIME * Only annotations declared for the RUNTIME life cycle can be obtained by 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(a) {
        super(a); }@MyAnnotation(value = "jack")
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
    
    public void walk(a){
        System.out.println("In the process of learning...");
    }
    public void eat(a){
        System.out.println("Among the fish..."); }}Copy the code

Use of the four basic meta-annotations in the JDK 2

  • @Target: Used to modify the Annotation definition, which specifies which program elements the modified Annotation can be used to modify. @target also contains a member variable named value.

  • @Documented
    Copy the code

    : The Annotation class used to specify that this meta-annotation is decorated will be extracted into a document by the Javadoc tool. By default, Javadoc does not include annotations.

    • An annotation defined as Documented must have a Retention value of RUNTIME.
  • @Inherited
    Copy the code

    The Annotation it modifies will be inheritable. If a class uses an Annotation decorated with @Inherited, its subclasses automatically have that Annotation.

    • For example, if a custom annotation with the @Inherited annotation is annotated at the class level, a child class can inherit the annotation at the class level of its parent
    • In practical application, it is seldom used
import org.junit.Test;

import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.Date;

* meta annotations: Annotations that explain existing annotations * Retention: Specifies the lifetime of the Annotation being modified: SOURCE\CLASS (default behavior) \RUNTIME * Only annotations declared for the RUNTIME life cycle can be obtained by reflection. * ******* ******* * Documented: Indicates that the modified Annotation remains when it is resolved by Javadoc. Inherited: The annotations it modifies will have inheritance. * * 5. Annotate information by reflection -- to reflect the content of the system to explain */
public class AnnotationTest {
    public static void main(String[] args) {}@Test
    public void testGetAnnotation(a){
        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(a) {
        super(a); }@MyAnnotation
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @MyAnnotation
    public void walk(a){
        System.out.println("In the process of learning...");
    }
    public void eat(a){
        System.out.println("Among the fish..."); }}@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE,TYPE_PARAMETER,TYPE_USE})
public @interface MyAnnotation {
    String value(a) default "book";
}
Copy the code

Use reflection to obtain annotation information

  • JDK 5.0 injava.lang.reflectAdded under packageAnnotatedElementInterface that represents a program element in a program that can accept annotations
  • When aAnnotationThe type is defined as run-timeAnnotationAfter, the annotation is visible at runtime, whenclassThe file is saved at load timeclassIn the fileAnnotationThe vm reads the data
  • The program can callAnnotatedElementObject to access the following methodsAnnotationinformation

2.7 new features in JDK8: repeatable annotations

Java 8 offers two improvements to annotation handling: repeatable annotations and annotations that can be used for types. In addition, reflection has been enhanced to get the names of method parameters in Java8. This simplifies annotation on method parameters.

Examples of repeatable annotations:

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import static java.lang.annotation.ElementType.*;

@Retention(RetentionPolicy.RUNTIME)
@Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE})
public @interface MyAnnotations {

    MyAnnotation[] value();
}
123456789101112
import java.lang.annotation.*;
import static java.lang.annotation.ElementType.*;

@Repeatable(MyAnnotations.class)
@Retention(RetentionPolicy.RUNTIME)
@Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE,TYPE_PARAMETER,TYPE_USE})
public @interface MyAnnotation {

    String value(a) default "hello";

}
1234567891011
import java.lang.annotation.Annotation;

New features in JDK 8: repeatable annotations, type annotations ** 6.1 repeatable annotations: ① Declare on MyAnnotation@Repeatable, the member value is MyAnnotations. Class * ② MyAnnotation Target and Retention meta annotations are the same as MyAnnotations. * * *@author subei
 * @createThe 2020-05-11 11:19 * /
public class AnnotationTest {
    public static void main(String[] args) {}}@MyAnnotation(value = "hi")
@MyAnnotation(value = "abc")
// JDK 8:
//@MyAnnotations({@MyAnnotation(value="hi"),@MyAnnotation(value="hi")})
Copy the code

2.8 new in JDK8: type annotations

  • After JDK1.8, about meta-annotations@TargetParameter type ofElementTypeTwo more enumerations:TYPE_PARAMETER,TYPE_USE.
  • Before Java8, annotations could only be used where they were declared. Beginning with Java8, annotations could be applied anywhere.
    • ElementType.TYPE_PARAMETERIndicates that the annotation can be written in declarations of type variables (e.g., generic declarations).
    • ElementType.TYPE_USEIndicates that the annotation can be written in any statement that uses a type.
import java.util.ArrayList;

New features in JDK 8: repeatable annotations, type annotations ** 6.1 repeatable annotations: ① Declare on MyAnnotation@Repeatable, the member value is MyAnnotations. Class * ② MyAnnotation Target and Retention meta annotations are the same as MyAnnotations. * * 6.2 Type annotations: * elementType. TYPE_PARAMETER indicates that the annotation can be written in declarations of type variables (e.g., generic declarations). * elementType. TYPE_USE indicates that the annotation can be written in any statement that uses a type. * * /
public class AnnotationTest {}class GenericThe < @MyAnnotation T>{

    public void show(a) throws @MyAnnotation RuntimeException{

        ArrayList<@MyAnnotation String> list = new ArrayList<>();

        int num = (@MyAnnotation int) 10L; }}Copy the code

MyAnnotation

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(a) default "hello";

}
Copy the code