Enumeration and annotation

Time:2021-10-19

Use of enumerations

1. Introduction to enumeration

  • 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 (bank card), CreditCard (credit card).
    Employment status: busy, free, vocation, dimission
    Order status: unpaid, paid, delivered, return, checked, fulfilled
    Thread status: create, ready, running, blocking, dead
  • Enumeration classes are strongly recommended when you need to define a set of constants
  • Implementation of enumeration class
    You need to customize the enumeration class before JDK1.5
    New in JDK 1.5enumKeyword is used to define an enumeration class
    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 they should be usedprivate finalmodification
    Use of enumeration classesprivate finalThe decorated property 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

2. How to customize enumeration classes (before JDK 5.0)

  1. PrivatizationClass constructor, which guarantees 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 asprivate final, and initialized in the constructor
  4. Other requirements: get the properties of the enumeration object
//Custom enumeration class
class Season {
    //1. Declare season attribute
    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 season spring = new season ("spring", "spring flowers bloom");
    Public static final season summer = new season ("summer", "hot summer");
    Public static final season autumn = new season ("autumn", "crisp autumn");
    Public static final season winter = new season ("winter", "ice and snow");

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

    public String getSeasonDesc() {
        return seasonDesc;
    }

    @Override
    public String toString() {
        return "Season{" +
                "seasonName='" + seasonName + '\'' +
                ", seasonDesc='" + seasonDesc + '\'' +
                '}';
    }
}
public class SeasonTest {
    public static void main(String[] args) {
        System.out.println(Season.AUTUMN);// Season {seasonname = 'Autumn', seasondesc = 'crisp autumn'}
    }
}

3. How to use the keyword (JDK 5.0) enum to define enumeration classes

  • instructions
    useenumDefined enumeration classInherited by default java.lang.EnumClass, so you can no longer inherit other classes
    Constructor of enumeration class can only useprivatePermission modifier
    All instances of an enumeration class must be explicitly listed in the enumeration class(, separation; ending)。 The listed instances are automatically addedpublic static finalmodification
    The enumeration class object must be declared on the first line of the enumeration class
  • JDK 1.5Can be inswitchUsed in expressionsEnumThe object of the defined enumeration class is used as an expression,caseClause can directly use the name of the enumeration value without adding an enumeration class as a qualification.
  • Use steps
    1. Provide multiple objects of the current enumeration class: multiple objects are separated by commas, and the end object ends with a semicolon
    2. Declare properties of a custom enumeration class
    3. Privatize the constructor of the class and assign values to the object properties
    4. Other requirements: get the properties of the enumeration object
//Custom enumeration class
enum Season1 {
    //1. Provide multiple objects of the current enumeration class: multiple objects are separated by commas, and the end object ends with a semicolon
    Spring ("spring", "spring flowers bloom"),
    Summer ("summer", "hot summer"),
    Autumn ("autumn", "cool autumn"),
    Winter ("winter", "ice and snow");

    //2. Declare the Season1 attribute
    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 requirements: get the properties of enumeration objects
    public String getSeasonDesc() {
        return seasonDesc;
    }

    public String getSeasonName() {
        return seasonName;
    }
}

public class SeasonTest1 {
    public static void main(String[] args) {
        System.out.println(Season1.WINTER);//WINTER
        System.out.println(Season1.class.getSuperclass());//class java.lang.Enum
    }
}

4. Main methods of enum (JDK 1.5)

  • java.lang public abstract class Enum> extends Object implements Comparable, Serializable
Protected enum (string name, int ordinal) is a unique constructor. The programmer cannot call this constructor. 
    It is used by code issued by the compiler in response to enumeration type declarations.
Protected object clone() enumeration type cannot be clone. To prevent subclasses from implementing clone methods, 
    Enum implements an invariant clone () that throws a clonenotsupportedexception exception.  
The int CompareTo (e o) enumeration type implements the comparable interface, which allows you to compare the size of two enumeration constants (sorted in the declared order).  
Boolean equals (object other) can directly use "= =" in enumeration types to compare whether two enumeration constants are equal.
    Enum provides this equals() method, which is also implemented directly with "= =". It exists for use in set, list and map. Note that equals() is immutable  
Protected void finalize() enumeration class cannot have a finalize method.  
Class getdeclarangclass() gets the class object of the enumeration type to which the enumeration constant belongs. It can be used to judge whether two enumeration constants belong to the same enumeration type. 
Int hashcode() enum implements hashcode() to be consistent with equals(). It is also immutable.  
String name() returns the name of this enumeration constant, exactly as declared in its enumeration declaration.  
Int ordinal() returns the ordinal of this enumeration constant (the position in its enumeration declaration, where the ordinal of the initial constant is zero).  
String tostring() gets the name of the current enumeration constant. You can make the results easier to read by writing this method  
Static > t valueof (class enumtype, string name) passes the class object and enumeration constant name of the enumeration type
    Given the static method valueof, you will get the enumeration constant matching the parameter.


values();  Returns an array of enumerated objects. This method can easily traverse all enumerated values
valueOf(String str);  You can convert a string to the corresponding enumeration object. The string must be the "name" of the enumeration object. If not, there will be a runtime exception 
    IllegalArgumentException.
toString();  Returns the name of the current enumeration object constant
  • Methods inherited from class java.lang.Object : getClass, notify, notifyAll, wait, wait, wait

5. Enumeration class that implements the interface

  • 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
//Case 1: implement the interface and implement the abstract method in the enum class
//Case 2: let the enumerated objects implement the abstract methods in the interface respectively
interface Info {
    void show();
}

//Custom enumeration class
enum Season1 implements Info {
    //1. Provide multiple objects of the current enumeration class: multiple objects are separated by commas, and the end object ends with a semicolon
    Spring ("spring", "spring flowers bloom"){
        @Override
        public void show() {
            System. Out. Println ("where is spring");
        }
    },
    Summer ("summer", "hot summer"){
        @Override
        public void show() {
            System.out.println ("Ningxia");
        }
    },
    Autumn ("autumn", "cool autumn"){
        @Override
        public void show() {
            System. Out. Println ("don't come back in autumn");
        }
    },
    Winter ("winter", "ice and snow"){
        @Override
        public void show() {
            System.out.println ("about winter");
        }
    };

    //2. Declare the Season1 attribute
    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;
    }


    //5. Other requirements: get the properties of enumeration objects
    public String getSeasonDesc() {
        return seasonDesc;
    }

    public String getSeasonName() {
        return seasonName;
    }

    /*@Override
    public void show() {
        System. Out. Println ("this is a season");
    }*/
}
//Call: Season1. Autumn. Show();

exercises

  1. What is an enumeration class? What are the modifiers of the object declaration of the enumeration class?
    Enumeration class; The number of objects in the class is determined and limited
    private final (No)
    public static final (yes)

Use of annotations

1. Annotation overview

  • Since JDK 5.0, Java has added metadata(MetaData)Support, that isAnnotation(note)
  • AnnotationIt’s actually in the codeSpecial mark, these tags can be read and processed at compile time, class load time, and runtime. through the use ofAnnotation, 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.
  • AnnotationCan be used like modifiers forModify the declaration of packages, classes, constructors, methods, member variables, parameters and local variables, this information is stored inAnnotationYes“name=value”Center.
  • stayJavaSEIn, annotations are used for simple purposes, such as marking outdated functions, ignoring warnings, etc. stayJavaEE/AndroidAnnotations play a more important role, 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 based on annotations,JPAIt’s annotation based,Spring2.5The above is based on annotations,Hibernate3.xIt will also be based on annotations in the future, and now it isStruts2Some of them are also based on annotation. Annotation is a trend. To some extent, it can be said:Frame = annotation + reflection + design pattern

2. Common annotation examples

  • useAnnotationAdd in front of it@Symbols, andUse the annotation as a modifier。 Used to decorate the program elements it supports

  • Example 1: generate document related annotations

    • @authorIndicate the author who develops this kind of module, which can be used and divided among multiple authors
    • @versionIndicate the version of such modules
    • @seeReference turn, that is, related topics
    • @sinceWhich version was added from
    • @paramThe description of a parameter in the method. If there is no parameter, it cannot be written
    • @returnDescription of the return value of the method. If the return value type of the method is void, it cannot be written
    • @exceptionDescribe the possible exceptions thrown by the method. If the method does not explicitly throw an exception with throws, it cannot be written to it
      @Param @ return and @ exception are only used for [email protected] 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
      image
  • Example 2:Format checking at compile time (three basic annotations built into JDK)
    @Override: qualified to override the parent class method. 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
    image

  • Example 3: track code dependencies and implement the function of replacing configuration files
    Servlet 3.0 provides annotation, which eliminates the need for servlet deployment in the web.xml file.

3. User defined annotation

  • Define a new annotation type using@interfacekeyword
  • Custom annotations are automatically inheritedjava.lang.annotation.AnnotationInterface
  • AnnotationMember variables inAnnotationThe definition is declared as a parameterless method. Its method name and return value define the name and type of the member. We call it configuration parameters. The type can only be eight basic data typesString type, class type, enum type, annotation type, and arrays of all the above types
  • Can be defined inAnnotationSpecifies the initial value of a member variable, which can be used to specify the initial value of a member variableDefault keyword
  • If there is only one parameter member, it is recommended to useThe parameter name is 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 calledsign; Annotations that contain member variables are called metadata annotations
  • be careful:A custom annotation must be accompanied by an annotation’s information processing flow (reflection) to be meaningful.
//1. The annotation is declared as @ interface
public @interface MyAnnotation {
    //2. Internally defined members are usually represented by value
    //3. You can use the default value of the specified member and use the default definition
    //4. If the user-defined annotation has no member, it indicates that it is a representation function
    String vale() default "hello";
}
//5. If the annotation has members, you need to specify the member value when using the annotation
//@MyAnnotation(vale = "hello")
@MyAnnotation
class test {
    public static void main(String[] args) {

    }
}

4. Meta annotation in JDK

  • The meta annotation of JDK (annotation describing existing annotations) is used to modify other annotation definitions
  • Jdk5.0 provides four standard meta annotation types:
    RetentionSpecifies the declaration period of the decorated annotation
    TargetUsed to specify which program elements can be modified by the modified annotation
    DocumentedWhen the modified annotation is parsed by Javadoc, it is retained
    InheritedThe annotation modified by it will be inherited (get annotation information through reflection)

Understanding of metadata:
String name = “atguigu”;

  • @Retention: can only be used to decorate oneAnnotationDefinition that specifies theAnnotationThe life cycle of,@RententionContains oneRetentionPolicyMember variables of type, using@RententionMust be thevalueSpecify values for member variables:
    RetentionPolicy.SOURCE: valid in the source file (i.e. source file retention), the compiler directly discards the comments of this policy
    RetentionPolicy.CLASS: it is 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 run time (i.e. reserved at run time),When you run a java program, the JVM keeps comments. The program can get the comment through reflection
    image

  • @Target: used to modify the annotation definition. It is used to specify which program elements can be modified by the modified [email protected] Target also contains a member variable named value.

    Value (element type) describe
    constructor Used to describe constructors
    field Used to describe a domain
    local_varibable Used to describe local variables
    method Used to describe the method
    package Used to describe the package
    parameter Used to describe parameters
    type Used to describe classes, interfaces (including annotation types) or enum declarations
  • @Documented: used to specify the element to beAnnotationEmbellishedAnnotationClass 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: decorated by itAnnotationWill haveInheritance。 If a class uses @ inherited modifiedAnnotation, its subclasses will automatically have the annotation.
    For example, if you mark@InheritedThe custom annotation of annotation is marked at the class level, and the subclass can inherit the annotation at the parent class level
    In practical application, it is less used

5. Use reflection to obtain annotation information

  • 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 read by the virtual machine
  • The program can call the following methods of the annotatedelement object to access the annotation information
    image

6. New features of annotations in JDK 8

  • Java 8 provides two improvements to annotation processing:Repeatable annotationandAnnotations available 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.
  • Repeatable annotation
    1. Declare @ repeatable on myannotation, and the member value is myannotations.class
    2. The target and retention meta annotations of myannotations are the same as myannotations
      Writing before jdk8
    //1. The annotation is declared as @ interface
    public @interface MyAnnotation {
    	//2. Internally defined members are usually represented by value
    	//3. You can use the default value of the specified member and use the default definition
    	//4. If the user-defined annotation has no member, it indicates that it is a representation function
    	String vale() default "hello";
    }
    
    //5. If the annotation has members, you need to specify the member value when using the annotation
    @interface MyAnnotations {
    	MyAnnotation[] value();
    }
    
    @MyAnnotations({@MyAnnotation(vale = "b"), @MyAnnotation(vale = "a")})
    class Test {
    
    }

    jdk8

    //1. The annotation is declared as @ interface
    @Repeatable(MyAnnotations.class)
    public @interface MyAnnotation {
    	//2. Internally defined members are usually represented by value
    	//3. You can use the default value of the specified member and use the default definition
    	//4. If the user-defined annotation has no member, it indicates that it is a representation function
    	String vale() default "hello";
    }
    
    //5. If the annotation has members, you need to specify the member value when using the annotation
    @interface MyAnnotations {
    	MyAnnotation[] value();
    }
    
    @MyAnnotation(vale = "123")
    @MyAnnotation(vale = "abc")
    class Test {
    
    }
  • type annotation
    • After JDK1.8, about meta annotation@TargetParameter type forElementTypeThere are two more enumeration values: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_PARAMETERIndicates that the annotation can be written in the declaration statement of type variables (e.g. generic declaration).
      ElementType.TYPE_USEIndicates that the annotation can be written in any statement using the type.
    class TestTypeDefine {
    	private U u;
    
    	public  void test(T t) {
    	}
    }
    
    @Target({ElementType.TYPE_PARAMETER})
    @interface TypeDefine {
    }

exercises

  • What is far view annotation? Talk about the role of retention and target meta annotations
    Meta annotation; A note that explains an existing note
    retention; Indicates the declaration cycle of the modified annotation, source class runtime

Recommended Today

OC basis

IOS development interview essential skills chart.png What are objects and what are the objects in OC? An object is an instance of a class; Is an instance created through a class, which is generally called an instance object; Common objects in OC include instance objects, class objects, and metaclass objects; What is a class? What […]