[Java] Enumeration classes and annotations

Table of contents

1. The use of enumeration classes

1. Description of the enumeration class:

2. How to customize the enumeration class?

3. JDK 5.0 adds the use of enum to define enumeration classes.

Second, the use of annotations

1. Understanding of annotations

2. An example of using annotations

3. How to customize annotations

4. Meta annotations:

5. How to get annotation information:

6. New features of annotations in JDK 8.0:


1. The use of enumeration classes

1. Description of the enumeration class:

  1. The understanding of enumeration classes: there are only a limited number of objects of the class, which is definite. We call this class an enum class

  2. When you need to define a set of constants, it is strongly recommended to use enumeration classes

  3. Implementation of the enumeration class:

    Prior to JDK 5.0 a custom

    After JDK 5.0, the new enum keyword is used to define enumeration classes

  4. If there is only one object in the enumeration class, it can be used as the implementation of the singleton pattern.

  5. Attributes of the enumeration class:

    The properties of the enumeration class object should not be allowed to be changed, so private final should be used to modify the properties of the enumeration class that are modified with private final should be assigned in the constructor If the enumeration class explicitly defines a constructor with parameters , then the corresponding incoming parameters must also be passed in when listing enumeration values

2. How to customize the enumeration class?

step:

  1. The private constructor ensures that its objects cannot be created outside the class;
  2. Example of creating an enum class inside a class. Declared as: public static final;
  3. If the object has instance variables, it should be declared as private final and initialized in the constructor;

Code example:

//自定义枚举类
class Season{
    //1.声明Season对象的属性:private final修饰
    private final String seasonName;
    private final String seasonDesc;

    //2.私化类的构造器,并给对象属性赋值
    private Season(String seasonName,String seasonDesc){
        this.seasonName = seasonName;
        this.seasonDesc = seasonDesc;
    }

    //3.提供当前枚举类的多个对象:public static final的
    public static final Season SPRING = new Season("春天","春暖花开");
    public static final Season SUMMER = new Season("夏天","夏日炎炎");
    public static final Season AUTUMN = new Season("秋天","秋高气爽");
    public static final Season WINTER = new Season("冬天","冰天雪地");

    //4.其他诉求1:获取枚举类对象的属性
    public String getSeasonName() {
        return seasonName;
    }

    public String getSeasonDesc() {
        return seasonDesc;
    }
    //4.其他诉求1:提供toString()
    @Override
    public String toString() {
        return "Season{" +
            "seasonName='" + seasonName + '\'' +
            ", seasonDesc='" + seasonDesc + '\'' +
            '}';
    }
}

复制代码

3. JDK 5.0 adds the use of enum to define enumeration classes.

Instructions for use:

  • The enumeration class defined using enum inherits  java.lang.Enum the class by default, so it cannot inherit other classes

  • The constructor of the enumeration class can only use the private permission modifier

  • All instances of an enum class must be explicitly listed within the enum class ( , separated  ; at the end). The listed instance system will automatically add public static final decorations

  • The enum class object must be declared on the first line of the enum class

Code example:

//使用enum关键字枚举类
enum Season1 {
    //1.提供当前枚举类的对象,多个对象之间用","隔开,末尾对象";"结束
    SPRING("春天","春暖花开"),
    SUMMER("夏天","夏日炎炎"),
    AUTUMN("秋天","秋高气爽"),
    WINTER("冬天","冰天雪地");

    //2.声明Season对象的属性:private final修饰
    private final String seasonName;
    private final String seasonDesc;

    //2.私化类的构造器,并给对象属性赋值

    private Season1(String seasonName,String seasonDesc){
        this.seasonName = seasonName;
        this.seasonDesc = seasonDesc;
    }

    //4.其他诉求1:获取枚举类对象的属性
    public String getSeasonName() {
        return seasonName;
    }

    public String getSeasonDesc() {
        return seasonDesc;
    }

}

复制代码

Common methods of the Enum class:

  1. values()Method: Returns an array of objects of the enumeration type. This method can easily traverse all enumeration values.

  2. valueOf(String str): You can convert a string into the corresponding enumeration class object. It is required that the string must be the "name" of the enumeration class object. If not, there will be a runtime exception IllegalArgumentException

  3. toString(): Returns the name of the current enumeration class object constant

Code example:

Season1 summer = Season1.SUMMER;
//toString():返回枚举类对象的名称
System.out.println(summer.toString());

//        System.out.println(Season1.class.getSuperclass());
System.out.println("****************");
//values():返回所的枚举类对象构成的数组
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):返回枚举类中对象名是objName的对象。
Season1 winter = Season1.valueOf("WINTER");
//如果没objName的枚举类对象,则抛异常:IllegalArgumentException
//        Season1 winter = Season1.valueOf("WINTER1");
System.out.println(winter);

复制代码

The enumeration class objects defined by the Enum class implement the interface respectively:

Instructions for use:

  1. Like ordinary Java classes, enumeration classes can implement one or more interfaces
  2. If each enumeration value exhibits the same behavior when calling the implemented interface method, it is only necessary to implement the method uniformly.
  3. If you need each enumeration value to behave differently when calling the implemented interface method, you can let each enumeration value implement the method separately

Code example:

interface Info{
    void show();
}

//使用enum关键字枚举类
enum Season1 implements Info{
    //1.提供当前枚举类的对象,多个对象之间用","隔开,末尾对象";"结束
    SPRING("春天","春暖花开"){
        @Override
        public void show() {
            System.out.println("春天在哪里?");
        }
    },
    SUMMER("夏天","夏日炎炎"){
        @Override
        public void show() {
            System.out.println("宁夏");
        }
    },
    AUTUMN("秋天","秋高气爽"){
        @Override
        public void show() {
            System.out.println("秋天不回来");
        }
    },
    WINTER("冬天","冰天雪地"){
        @Override
        public void show() {
            System.out.println("大约在冬季");
        }
    };
}

复制代码

Second, the use of annotations

1. Understanding of annotations

① New features of jdk 5.0

② Annotation is actually a special mark in the code. These marks can be read during compilation, class loading, and runtime, and perform corresponding processing. By using Annotation, programmers can embed some supplementary information in source files without changing the original logic.

③ Annotation can be used like a modifier. It can be used to modify the declaration of packages, classes, constructors, methods, member variables, parameters, and local variables. These information are stored in the Annotation pair  name = value .

④ In JavaSE, the purpose of annotations is relatively simple, such as marking outdated functions, ignoring warnings, etc. Annotations occupy a more important role in JavaEE/Android, for example, to configure any aspects of the application, replacing the cumbersome code and XML configuration left in the old version of JavaEE.

⑤ Framework = annotation + reflection mechanism + design pattern

2. An example of using annotations

When using Annotation, add  @ a symbol in front of it, and use the Annotation as a modifier. Used to decorate the program elements it supports

Example 1: Generate documentation-related annotations

  • @author Indicate the author who developed this type of module, use among multiple authors, and  @version mark the version of this type of module separately;

  • @see Reference turn, that is, related topics;

  • @since From which version was added;

  • @param For the description of a parameter in the method, if there is no parameter  @return , the description of the return value of the method cannot be written. If the return value type of the method is ,   the description of the exception that the method may throw  void cannot be written  . If the method does not  explicitly throw exceptions cannot be written;@exceptionthrows

  • Among them  @param ,  @return and  @exception these three tags are only used for methods.

  • @param Format requirements: @param parameter name parameter type parameter description;

  • @return Format requirements: @return return value type return value description;

  • @exception Format requirements: @exception exception type exception description;

  • @param and  @exception can be multiple in parallel;

Code example:

/**
 * @author bruce
 * @project_name JavaSenior
 * @package_name com.bruce.java
 * @create 2020-04-26 10:58
 */
public class AnnotationTest {
    /**
     *程序的主方法
     * @param args 传入命令行参数
     */
    public static void main(String[] args) {

    }

    /**
     * 求圆形面积
     * @param radius 所求面积的半径
     * @return 面积值
     */
    public static double getArea(double radius){
        return Math.PI * radius * radius;
    }
}

复制代码

Example 2: Format checking at compile time (a basic annotation built into JDK)

  • @Override: Restricted to rewrite the parent class method, this annotation can only be used for methods;
  • @Deprecated: Used to indicate that the decorated element (class, method, etc.) is obsolete. Usually because the modified structure is dangerous or better alternatives exist;
  • @SuppressWarnings: suppress compiler warnings;

Code example:

public class AnnotationTest{
    public static void mian (String [] args){
        @SuppressWarning("unused")
        int a = 0;
    }
    @Deprecated
    public void print(){
        System.out.print("过时的方法");
    }
    @Override
    public String toString(){
        return "重写的toString方法";
    }
}

复制代码

Example Three: Tracking Code Dependencies and Implementing Alternative Configuration File Functions

Annotation-driven development is heavily used when using the Spring framework.

3. How to customize annotations

Refer to  @SuppressWarnings the definition

  1. The annotation declaration is:@interface
  2. Internally defined members, usually represented by value
  3. You can specify the default value of the member, using the default definition
  4. If the custom annotation has no members, it indicates that it is an identification function.

illustrate:

  • If the annotation has members, you need to specify the value of the member when using the annotation.

  • Custom annotations must be accompanied by the annotated information processing flow (using reflection) to make sense.

  • Custom annotations will specify two meta-annotations: @Retention@Target

    Code example:

@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";
}

复制代码

4. Meta annotations:

An annotation that explains an existing annotation.

Four meta-annotations provided by JDK 5.0:

  1. @Retention: Specify the life cycle of the modified Annotation: SOURCE\CLASS (default behavior)\RUNTIME Only annotations declared as RUNTIME life cycle can be obtained through reflection.
  2. @Target: Used to specify which program elements the modified Annotation can be used to modify

  3. @Documented: Indicates that the modified annotation is retained when parsed by javadoc.
  4. @Inherited: Annotation modified by it will be inherited.

Analogy: the concept of metadata: String name = "Tom"; modification of existing data

5. How to get annotation information:

Get and call by launching.

Premise: The life cycle state declared in the meta-annotation Retention of this annotation is required to be: RUNTIME.

6. New features of annotations in JDK 8.0:

Repeatable Annotations, Type Annotations

6.1 Repeatable annotations:

@Repeatabl① Declare e  on MyAnnotation  , the member value isMyAnnotations.class

② Meta-annotations such as Target and Retention of MyAnnotation are the same as MyAnnotations.

6.2 Type annotations:

ElementType.TYPE_PARAMETER Indicates that the annotation can be written in the declaration statement of the type variable (eg: generic declaration.)

ElementType.TYPE_USE Indicates that the annotation can be written in any statement that uses the type.


 

 

Guess you like

Origin blog.csdn.net/SFalS/article/details/127183212