“This article has participated in the good article call order activity, click to see: back end, big front end double track submission, 20,000 yuan prize pool for you to challenge!”

Little drops of water wear through a stone 😄

What is enumeration

Enumerations, a new feature introduced in JDK 1.5, consist of a fixed set of constants that make up the types of legal values, such as the season of the year, the number of weeks of the week. Enumeration is a special class that inherits the Java.lang. Enum class and implements the interfaces of java.lang.Seriablizable and java.lang.Comparable. Domain members are constant, and constructors are private by default.

How to Define an enumeration

Let’s see how enumerations are defined first! We define four values, spring, summer, fall, and winter.

public enum SeasonEnum {
    / / in the spring
    SPRING,
    / / in the summer
    SUMMER,
    / / fall
    AUTUMN,
    / / in the winter
    WINTER;
}
Copy the code

This is how enumerated classes are defined. Very simple! Let’s look at the functions provided by the enumeration class.

Enumerated function

public static void main(String[] args) {
    //1. Get the specified enumeration based on the name passed in, which may throw an exception
    SeasonEnum autumn = SeasonEnum.valueOf("AUTUMN");
    System.out.println("autumn1 = " + autumn);
    // Agree with 1
    SeasonEnum anEnum = SeasonEnum.valueOf(SeasonEnum.class, "AUTUMN");
    System.out.println("autumn2 = " +anEnum);
    //2, return all elements in the current enumeration class
    SeasonEnum[] values = SeasonEnum.values();
    System.out.println("values = " +Arrays.toString(values));
    //3, get the enumeration element
    SeasonEnum name1 = SeasonEnum.AUTUMN;
    System.out.println("name1 = " + name1);
    // Get the name of the enumeration element
    String name2 = SeasonEnum.AUTUMN.name();
    System.out.println("name2 = " + name2);
    //4, return index of this enumeration element, starting from 0
    int ordinal = SeasonEnum.AUTUMN.ordinal();
    System.out.println("ordinal = " + ordinal);
    Return a negative, zero, or positive integer for comparison with the specified object.
    // Less than the specified object returns a negative integer
    // returns zero for the specified object
    // Greater than the specified object returns a positive integer
    int i = SeasonEnum.AUTUMN.compareTo(SeasonEnum.AUTUMN);
    System.out.println("compareTo = " + i);
    // Return the type of the enumerated class
    System.out.println("getDeclaringClass = " + SeasonEnum.AUTUMN.getDeclaringClass());
    // Return true if the specified object is equal to this enumeration element.
    System.out.println("equals = " + SeasonEnum.AUTUMN.equals("AUTUMN")); } the result:  autumn1 = AUTUMN autumn2 = AUTUMN values = [SPRING, SUMMER, AUTUMN, WINTER] name1 = AUTUMN name2 = AUTUMN ordinal =2
compareTo = 0
getDeclaringClass = class com.gongj.jsondate.controller.SeasonEnum
equals = false
Copy the code

Use of enumerations

The above has simply introduced the definition of enumeration and enumeration function! This section will show you how and where to use enumerations at work!

1. Define constants

We use the SeasonEnum above to enumerate the class.

public static void main(String[] args) {
    SeasonEnum type = SeasonEnum.AUTUMN;
    if(SPRING.equals(type)){
        System.out.println("Spring: Spring blossoms.");
    }
    if(SUMMER.equals(type)){
        System.out.println("Summer: the heat of the summer sun.");
    }
    if(AUTUMN.equals(type)){
        System.out.println("Autumn: The autumn wind blows.");
    }
    if(WINTER.equals(type)){
        System.out.println("Winter: Warm winter sun"); }} Result: Autumn: The wind blows gently in autumnCopy the code

If and switch values can be replaced with enumerations to improve code readability.

2. Parameter receiving

Interface request parameter values can be received with enumerations! For example, the type of the orderType field of the OrderDTO class can be received using an enumeration! What good is that?

  • 1. Code readability allows other developers to know at a glance what the order type has (values).
  • 2. Specify the scope of the order type. It prevents users from passing arbitrary values.
public class OrderDTO {

   private Long id;

   private String orderName;

   private SeasonEnum orderType;
}
Copy the code

The SeasonEnum enum class is used here again.

Provide external interfaces

@PostMapping("/save")
public void save(@RequestBody OrderDTO req){
    System.out.println( JSON.toJSONString(req));
}
Copy the code

Then the calling: http://localhost:8080/save, prompt response value is not a statement of Enum one instance name.

That is, the value of orderType can only enumerate the declared instances of the SeasonEnum class.

3, code value conversion

Using an enumeration class implementation eliminates many of the if/else’s. Most are used to connect to different systems, such as: to connect to a bank docking function, the process is as follows: front end – “this system back end -” call the bank interface. There is a code value for the payment status. 1- pending payment in your system, and 0- pending payment in the bank. The code values between the two systems are inconsistent. Therefore, the system needs to configure conversion rules. This is where you can use enumerated classes.

3.1. Write an enumeration base class

Write an enumeration base class, all enumeration classes need to implement this interface, if the base class does not meet the requirements, subclasses can extend at will.

public interface BaseEnum {

    String getKey(a);

    void setKey(String key);

    String getValue(a);

    void setValue(String value);

    String getDesc(a);

    void setDesc(String desc);
}
Copy the code

3.2. Write payment enumeration class

Implement the BaseEnum interface, extend the channel and channelDesc fields, and add the match method.

public enum PayEnum implements BaseEnum{
    WAITING_PAY("1"."0"."Pending payment"."unionpay"."Unionpay"),
    SUCCESS_PAY("2"."1"."Successful payment"."unionpay"."Unionpay"),
    FAIL_PAY("3"."2"."Payment failure"."unionpay"."Unionpay"),

    ALIPAY_WAITING_PAY("1"."3"."Pending payment"."alipay"."Alipay");

    private String key;
    private String value;
    private String desc;

    // This extended field is used to connect the payment status of different systems
    private String channel;
    private String channelDesc;

    private PayEnum(String key,String value,String desc,String channel,String channelDesc){
        this.key = key;
        this.value = value;
        this.desc = desc;
        this.channel = channel;
        this.channelDesc = channelDesc;
    }
    @Override
    public String getKey(a) {
        return this.key;
    }

    @Override
    public void setKey(String key) {
        this.key = key;
    }

    @Override
    public String getValue(a) {
        return this.value;
    }

    @Override
    public void setValue(String value) {
        this.value = value;
    }

    @Override
    public String getDesc(a) {
        return this.desc;
    }

    @Override
    public void setDesc(String desc) {
        this.desc = desc;
    }

    public String getChannel(a) {
        return channel;
    }

    public void setChannel(String channel) {
        this.channel = channel;
    }

    public String getChannelDesc(a) {
        return channelDesc;
    }

    public void setChannelDesc(String channelDesc) {
        this.channelDesc = channelDesc;
    }

    /** * Get enumeration instances based on key and channel *@param key
     * @param channel
     * @return* /
    public static PayEnum match(String key, String channel) {
        PayEnum[] enums = PayEnum.values();
        for (PayEnum payEnum : enums) {
            if (key.equals(payEnum.getKey()) && channel.equals(payEnum.getChannel()))
                return payEnum;
        }
        return null; }}Copy the code

3.3, tests,

public static void main(String[] args) {
    String key = "1";
    String channel = "unionpay";
    PayEnum match = match(key, channel);
    System.out.println(match.getKey() + "= =" + match.getValue() 
    + "= = =" + match.getDesc() + "= = =" + 
    "= ="+ match.getChannel()); } the result:1= =0=== to be paid =====unionpayCopy the code

With enumerations in some cases, you can leave out a lot of if/else.

  • If you have any questions or errors in this article, please feel free to comment. If you find this article helpful, please click like and follow.