Java枚举类型校验

2016/10/31 Java

原代码

package com.merryyou.enmu;

/**
 *
 * Created on 2016/10/31 0031.
 *
 * @author zlf
 * @since 1.0
 */
public class OriDemo {
    public static final String ADD = "add";
    public static final String INSERT = "insert";
    public static final String UPDATE = "update";
    public static final String DEL = "deltete";

    public static void main(String[] args) {
//        test("add");
        test("111");//参数不符合要求的时候也可以执行
    }

    public static void test(String str){
        switch (str){
            case ADD:
                System.out.println("add");
                break;
            case INSERT:
                System.out.println("insert");
                break;
            case UPDATE:
                System.out.println("update");
                break;
            case DEL:
                System.out.println("del");
                break;
            default:
                System.out.println("参数异常");
        }
    }
}

使用枚举之后

package com.merryyou.enmu;

import java.util.HashMap;
import java.util.Map;

/**
 * Created on 2016/10/31 0031.
 *
 * @author zlf
 * @since 1.0
 */
public enum Command {
    ADD("add"),
    INSERT("insert"),
    UPDATE("update"),
    DEL("delete");
    private String commandStr;
    Command(String str) {
        this.commandStr = str;
    }
    private static final Map<String, Command> stringToCommand = new HashMap<String, Command>();

    static {
        for(Command item : values()){
            stringToCommand.put(item.toString(), item);
        }
    }

    public static Command fromString(String commandStr){
        return stringToCommand.get(commandStr);
    }

    @Override
    public String toString() {
        return this.commandStr;
    }
}

package com.merryyou.enmu;

/**
 * Created on 2016/10/31 0031.
 *
 * @author zlf
 * @since 1.0
 */
public class CurDemo {
    public static void main(String[] args) {
        test(Command.ADD);
    }
    public static void test(Command command) {
        switch (command){
            case ADD:
                System.out.println("add");
                break;
            case INSERT:
                System.out.println("insert");
                break;
            case UPDATE:
                System.out.println("update");
                break;
            case DEL:
                System.out.println("del");
                break;
        }
    }

}


参考链接

Show Disqus Comments

Search

    Post Directory