Java enumeration (enum) details common usage

JDK1.5引入了新的类型--枚举,在java中虽然枚举只是一个很小的功能,却给我们带来了很大的方便。
首先我们要了解几个概念,enum是没有构造函数的,准确的来说是没有public类型的构造函数,
它的构造函数只能是private类型的;enum是单例模式;enum中有一个values方法来获取枚举实例对象数组;

Description: MSG_TYPE_SYSTEM is an enumeration constant, MsgTypeEnum is an enumeration class, see below for specific examples.
Obtain the corresponding enumeration instance object through the enumeration constant name:

MsgTypeEnum s = MsgTypeEnum.valueOf(MSG_TYPE_SYSTEM.name());

Get the bit order of enum constants in the enum class:

MSG_TYPE_SYSTEM.ordinal();
1. Usage 1: Constants

Before JDK1.5, we defined constants: public static final... . Well, related constants can now be grouped into enum types, and enums provide more methods than constants.

public enum Color {  
  RED, GREEN, BLANK, YELLOW  
}
2. Add a new method to the enumeration

If you plan to customize your own method, you must add a semicolon (";") at the end of the enum instance sequence. In java, you must define a java instance first.

package ggmsg.common;

public enum ChannelEnum {

    MSG_CENTER_CHANNEL1("msg_center_channel1"),
    MSG_CENTER_CHANNEL("msg_center_channel");

    private String channel = null;

    private ChannelEnum(String channel) {
        this.channel = channel;
    }

    public String getChannel() {
        return this.channel;
    }
}
3. Implement the interface

All enums inherit from the java.lang.Enum class. Since Java does not support multiple inheritance, enum objects can no longer inherit from other classes.

public interface Behaviour {  
    void print();  
    String getInfo();  
}  
public enum Color implements Behaviour{  
    RED("红色", 1), GREEN("绿色", 2), BLANK("白色", 3), YELLO("黄色", 4);  
    // 成员变量  
    private String name;  
    private int index;  
    // 构造方法  
    private Color(String name, int index) {  
        this.name = name;  
        this.index = index;  
    }  
//接口方法  
    @Override  
    public String getInfo() {  
        return this.name;  
    }  
    //接口方法  
    @Override  
    public void print() {  
        System.out.println(this.index+":"+this.name);  
    }  
}
4. Use interfaces to organize enumerations
package common.lang;

public interface Food {
    enum Coffee implements Food{  
        BLACK_COFFEE,DECAF_COFFEE,LATTE,CAPPUCCINO  
    }  
    enum Dessert implements Food{  
        FRUIT, CAKE, GELATO  
    }  
}
5. Use enumeration in switch

Before JDK1.6, switch only supported int and char, and after that, it supported the enum type, which made our code more readable.
First define an enumeration MsgTypeEnum class, and add the fromMsgType method to the class to obtain the enumeration instance object corresponding to the enumeration value through the enumeration value.

package ggmsg.common;

public enum MsgTypeEnum {
    //消息类型
    MSG_TYPE_SYSTEM(10001),
    //消息类型
    MSG_TYPE_LIVE_SYSTEM(10002),

    private int msgType;

    private MsgTypeEnum(int msgType){
        this.msgType = msgType;
    }

    public int getMsgType() {
        return this.msgType;
    }
    /**
     * 
     * 方法描述 根据类型的名称,返回类型的枚举实例。 
     *
     */
    public static MsgTypeEnum fromMsgType(int msgType) {  
        for (MsgTypeEnum type : MsgTypeEnum.values()) {  
            if (type.getMsgType() == msgType) {  
                return type;  
            }  
        }  
        return null;  
    } 
}

Define a switch statement in the method, obtain the corresponding enumeration instance object through the fromMsgType method, and write the name of the enumeration type directly after the case, so that we can use the enumeration in the switch statement.

public static void handleMsg(Msg msg) {
        try {
            GGLogger.info(GGMsgService.class, "\nWebSocket接收到的消息是:\n\n"+msg.toString());
            //消息类型
            MsgTypeEnum msgType = MsgTypeEnum.fromMsgType(msg.getMsg_type());
            switch (msgType) {
                //添加用户订阅信息
            case MSG_TYPE_ORDER:
                GGUserSubBuilder.addSubMsg(msg);
                break;
                //消息类型【系统消息】
            case MSG_TYPE_SYSTEM:

                break;
            default:
                break;
            }

        } catch (Exception e) {
            GGUserSubBuilder.sendMsg(msg.getWebSocket(), "WebSocket接收处理消息异常!"+e);
            GGLogger.error(GGMsgService.class, "WebSocket接收处理消息异常!"+e);
        }

    }

From the above example, we can see that the constructor of enum is private, and external classes are not allowed to obtain instances of enum through the new method.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325623563&siteId=291194637