Java enumeration classes and annotations

classification

  • Custom class enumeration
  • Implementation using enum keyword

Custom enumeration class code

  1. Constructor privatization to prevent direct new
  2. Remove the set related method to prevent the property from being modified
  3. Create fixed objects directly in Season
  4. To prevent the static method of the class from being loaded every time the program runs, add the keyword final
  5. Enumeration object names usually use all uppercase, and the naming convention of constants
// Custom enumeration
class Season {
    private String name;
    private String desc;

    // 3. Create fixed objects directly in Season
    // 4. To prevent the static method of the class from being loaded every time the program runs, add the keyword final
    public static final Season SPRING = new Season("spring","warm");
    public static final Season WINTER = new Season("winter","cold");
    public static final Season SUMMER = new Season("summer","scorching hot");
    public static final Season AUTUMN = new Season("autumn","pleasantly cool");

    // 1. Constructor privatization to prevent direct new
    // 2. Remove the set related method to prevent the property from being modified

    private Season(String name, String desc) {
        this.name = name;
        this.desc = desc;
    }

    public String getName() {
        return name;
    }


    public String getDesc() {
        return desc;
    }

    @Override
    public String toString() {
        return "Season{" +
                "name='" + name + '\'' +
                ", desc='" + desc + '\'' +
                '}';
    }
}

Keyword enumeration code

When using enum, the enum class is implicitly inherited

  1. Replace class with keyword enum
  2. Constant name (parameter list)
  3. If there are multiple constant objects, use, sign interval
  4. If enum is used to implement enumeration, it is required to write the definition constant object in front
  5. If you use a parameterless constructor to create a constant object, you can omit ()
  6. The enumeration object must be placed at the beginning of the line of the enumeration class
package com.xiaolu.enum_;

/**
 * @author Lin Xiaolu
 * @version 1.0
 */
public class Enumeration02 {
    public static void main(String[] args) {
        System.out.println(Season2.AUTUMN);
    }
}

// Using enum keyword to implement enumeration class
enum Season2 {


//    public static final Season SPRING = new Season("spring", "warm");
//    public static final Season WINTER = new Season("winter", "cold");
//    public static final Season SUMMER = new Season("summer", "hot");
//    public static final Season AUTUMN = new Season("autumn", "cool");

    // 1. Replace class with keyword enum
    // 2. Constant name (parameter list)
    // 3. If there are multiple constant objects, use, sign interval
    // 4. If enum is used to implement enumeration, it is required to write the definition constant object in front
    // 5. If you use a parameterless constructor to create a constant object, you can omit ()
    SPRING("spring","warm"), WINTER("winter","cold"), SUMMER("summer","scorching hot"),
    AUTUMN("autumn","pleasantly cool"), WHAT;
    private String name;
    private String desc;


    Season2() {
    }

    private Season2(String name, String desc) {
        this.name = name;
        this.desc = desc;
    }

    public String getName() {
        return name;
    }


    public String getDesc() {
        return desc;
    }

    @Override
    public String toString() {
        return "Season{" +
                "name='" + name + '\'' +
                ", desc='" + desc + '\'' +
                '}';
    }
}

Common enumeration class methods

  1. toString method: overridden, return enumeration object name
  2. name(): name of the output enumeration object
  3. ordinal(): the output is the order / number of the enumeration object, numbered from 0
  4. values(): you can see the values method by decompiling javap, and return an array containing all enumeration objects defined in Season2 []
  5. valueOf()
    • To convert a string into an enumeration object, the string must be VT as an existing constant name, or an error will be reported
    • According to the input "AUTUMN" to the enumeration object of Season2, if found, it will return; if not, it will report an error
  6. compareTo()
    • Compare two enumeration constants, the comparison is the number, and the two numbers are subtracted
    • Season2.AUTUMN No. [3] - Season2.SUMMER No. [2] = = [1]
    • If equal to zero, then equal

code

package com.xiaolu.enum_;

/**
 * @author Lin Xiaolu
 * @version 1.0
 * Demonstrates the use of various methods of the Enum class
 */
public class EnumMethod {

    public static void main(String[] args) {
        // Use the Season2 enumeration class as an example
        Season2 autumn = Season2.AUTUMN;
        System.out.println(autumn.name());  // The name of the output enumeration object
        System.out.println(autumn.ordinal());  // The output is the order / number of the enumeration object, numbered from 0
        Season2[] values = Season2.values();  // You can see the values method by decompiling javap, and return an array containing all enumeration objects defined in Season2 []
        System.out.println("===Traverse and get enumerated objects(enhance for)===");
        for (Season2 season : values) {// Enhanced for loop
            System.out.println(season);
        }

        Season2 autumn1 = Season2.valueOf("AUTUMN");  // To convert a string into an enumeration object, the string must be VT as an existing constant name, or an error will be reported
        // According to the input "AUTUMN" to the enumeration object of Season2, if found, it will return; if not, it will report an error
        System.out.println(autumn == autumn1);

        System.out.println(Season2.AUTUMN.compareTo(Season2.SUMMER));  // Compare two enumeration constants, the comparison is the number, and the two numbers are subtracted
        // Season2.AUTUMN No. [3] - Season2.SUMMER No. [2] = = [1]
        // If equal to zero, then equal


    }
}

enum details

  • After using the enum keyword, you can't inherit other classes, because enum implicitly inherits enum, and Java is a single inheritance mechanism
  • Enumeration classes, like ordinary classes, can implement interfaces

Annotation

  • @Override: restrict a method to override the parent class method. This annotation can only be used in methods

    • It can be used to mark and verify whether the method is really re compiled. If it is rewritten, the compilation passes; otherwise, the compilation is wrong
  • @Deprecated: used to indicate that a program element (class, method) is obsolete

    • You can modify methods, classes, fields, packages, parameters, etc
    • After use, it indicates that the class and method are outdated, and there will be a strikethrough in the middle, but they can still be used
    • It can be used for version upgrade, compatibility and transition
  • @SuppressWarnings: suppress compiler warnings

    • @SuppressWarnings({""})
      
    • In {""}, you can write the warning message you want to suppress (not display)

  • Supplement:

    • @Interface is not an interface interface, but an annotation class, which was added after jdk5.0
    • @Target is an annotation that modifies an annotation, called a meta annotation

Meta annotation

Used to decorate other annotations

  • type
    1. @Retention: Specifies the scope of the annotation. There are three types of source, class, and runtime
    2. @Target: specifies where annotations can be used
    3. @Documented: specify whether the annotation will be reflected in javadoc·
    4. @Inherited: the subclass will inherit the annotation of the parent class

Tags: Java jvm Spring

Posted by BooRadLey on Sun, 21 Aug 2022 09:29:12 +0300