Setting an Enum value based on incoming String

前端 未结 4 905
慢半拍i
慢半拍i 2021-02-08 06:10

I have a number of setter methods which take an enum. These are based on incoming objects attribute. Rather than write a bunch of these is there a way around having to hard code

4条回答
  •  有刺的猬
    2021-02-08 07:05

    You can implement that functionality in your Enum.

    public enum Side {
    
        BUY("B"), SELL("S"), ...
    
        private String letter;
        private Side(String letter) {
            this.letter = letter;
        }
    
        public static Side fromLetter(String letter) {
            for (side s : values() ){
                if (s.letter.equals(letter)) return s;
            }
            return null;
        }
    
    }
    

    You could also do this as a helper static method if you can't edit Side.

    public static Side fromString(String from) {
        for (Side s: Side.values()) {
            if (s.toString().startsWith(from)) {
                return s;
            }
        }
    
        throw new IllegalArgumentException( from );
    }
    

    The above method assumes your strings correspond to the names of you enums.

提交回复
热议问题