Enumeration classes and annotations

Keywords: Spring JDK Java Android

Enumeration classes and annotations

1, Use of enumeration classes

1. Understanding of enumeration class: there are only a limited number of objects in the class, which are certain. We call this class an enumeration class
2. When you need to define a set of constants, it is strongly recommended to use enumeration classes
3. If there is only one object in the enumeration class, it can be used as the implementation of singleton mode.

2, How to define enumeration class

Method 1: before jdk5.0, customize enumeration class

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 properties of the Season object: private final decoration
    private final String seasonName;
    private final String seasonDesc;

    //2. Privatize the constructor of the class and assign a value to the object property
    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 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","Scorching summer");
    public static final Season AUTUMN = new Season("Autumn","Fresh autumn weather");
    public static final 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;
    }
    //4. Other claims 1: toString()
    @Override
    public String toString() {
        return "Season{" +
                "seasonName='" + seasonName + '\'' +
                ", seasonDesc='" + seasonDesc + '\'' +
                '}';
    }
}

Mode 2: jdk5.0, enum keyword can be used to define enumeration class

public class SeasonTest1 {
    public static void main(String[] args) {
        Season1 summer = Season1.SUMMER;
        //toString(): returns the name of an enumeration class object
        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]);
            values[i].show();
        }
        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 in the enumeration class whose object name is objName.
        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);
        winter.show();
    }
}

interface Info{
    void show();
}

//Enumerating classes using the enum keyword
enum Season1 implements Info{
    //1. Provide the object of the current enumeration class, separate multiple objects with "," and end with ";"
    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","Scorching summer"){
        @Override
        public void show() {
            System.out.println("Ningxia");
        }
    },
    AUTUMN("Autumn","Fresh autumn weather"){
        @Override
        public void show() {
            System.out.println("Don't come back in autumn");
        }
    },
    WINTER("winter","A world of ice and snow"){
        @Override
        public void show() {
            System.out.println("About in winter");
        }
    };

    //2. Declare the properties of the Season object: private final decoration
    private final String seasonName;
    private final String seasonDesc;

    //2. Privatize the constructor of the class and assign a value to the object property
    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;
    }
//    //4. Other claims 1: toString()
//
//    @Override
//    public String toString() {
//        return "Season1{" +
//                "seasonName='" + seasonName + '\'' +
//                ", seasonDesc='" + seasonDesc + '\'' +
//                '}';
//    }

//    @Override
//    public void show() {
//        System.out.println("it's a season");
//    }
}

3, Common methods in 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 string is required to be the name of an enumeration class object. If not, there will be a runtime exception: IllegalArgumentException.
toString(): returns the name of the current enumeration class object constant

4, Implementation of the interface using enum class defined by enum keyword

Case 1: implement interface and abstract method in enum class
Case 2: let the objects of enumeration class implement the abstract methods in the interface respectively

5, Use of annotations

1. Understand Annotation:

① New features of jdk 5.0
② Annotation is actually a special tag in the code. These tags can be read during compilation, class loading, runtime, and corresponding processing. By using annotation,
The programmer 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 in Java EE play a more important role, such as configuring any aspect of the application instead of the tedious legacy of Java EE
Code and XML configuration.

2. Use example of announcement

Example 1: generate document related annotations
Example 2: format checking at compile time (three basic annotations built into JDK)
@Override: restrict override of parent method, this annotation can only be used for methods
@Deprecated: used to indicate that the decorated element (class, method, etc.) is obsolete. It's usually because the decorated structure is dangerous or there's a better choice
@SuppressWarnings: suppress compiler warnings
Example 3: tracking code dependency and realizing the function of replacing configuration file

3. How to customize annotation: refer to @ SuppressWarnings definition

① The annotation declaration is: @ interface
② Internally defined members, usually represented by value
③ You can specify the default value of a member, defined with default
④ If the custom annotation has no members, it indicates an identity function.
If the annotation has members, you need to indicate the value of the member when using the annotation.
A custom annotation must be accompanied by an annotation's information processing flow (using reflection) to make sense.
Two meta annotations will be indicated when the user-defined annotation passes: Retention and Target

4. Four meta annotations provided by JDK

Meta annotation: annotation explaining existing annotations
Retention: Specifies the lifecycle of the decorated Annotation: SOURCE\CLASS (default behavior) \ RUNTIME
Only annotations declared as RUNTIME lifecycles can be obtained by reflection.
Target: used to specify which program elements can be decorated by the decorated Annotation
Low frequency of occurrence
Documented: indicates that the modified annotation is preserved when it is parsed by javadoc.
Inherited: the Annotation decorated by it will be inherited.

5. Get annotation information through reflection - systematic explanation when reflecting content

6. New features of annotation in JDK 8: repeatable annotation and type annotation

6.1 repeatable notes:

① Declare @ Repeatable on myannotations with member value MyAnnotations.class
② MyAnnotations have the same Target and Retention meta annotations as MyAnnotations.

6.2 type notes:

Elementtype.type'parameter indicates that the annotation can be written in the declaration statement of type variable (such as generic declaration).
Elementtype.type'use indicates that the annotation can be written in any statement that uses a type.

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

    @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]);
        }
    }
}

//Before jdk 8:
//@MyAnnotations({@MyAnnotation(value="hi"),@MyAnnotation(value="hi")})
@MyAnnotation(value="hi")
@MyAnnotation(value="abc")
class Person{
    private String name;
    private int age;

    public Person() {
    }
    @MyAnnotation
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
    @MyAnnotation
    public void walk(){
        System.out.println("People walking");
    }
    public void eat(){
        System.out.println("People eat");
    }
}

interface Info{
    void show();
}

class Student extends Person implements Info{
    @Override
    public void walk() {
        System.out.println("Students walk");
    }
    public void show() {
    }
}

class Generic<@MyAnnotation T>{
    public void show() throws @MyAnnotation RuntimeException{
        ArrayList<@MyAnnotation String> list = new ArrayList<>();
        int num = (@MyAnnotation int) 10L;
    }
}
@Inherited
@Repeatable(MyAnnotations.class)
@Retention(RetentionPolicy.RUNTIME)
@Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE,TYPE_PARAMETER,TYPE_USE})
public @interface MyAnnotation {

    String value() default "hello";
}
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE})
public @interface MyAnnotations {

    MyAnnotation[] value();
}
Published 25 original articles, praised 0, visited 582
Private letter follow

Posted by nttaylor on Mon, 24 Feb 2020 03:11:21 -0800