Setting an Enum value based on incoming String

前端 未结 4 938
慢半拍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 06:47

    I ended up using a simple object map:

    private static HashMap<String, Side> sideMap = new HashMap<String, Side>(7);
    static{
        sideMap.put("B", Side.BUY);
        sideMap.put("S", Side.SELL);
    }
    

    and simply using

    Obj.setSide(sideMap.get(zasAlloc.getM_buySellCode()));
    
    0 讨论(0)
  • 2021-02-08 07:01

    Enums have valueOf() method that can be used to convert from String. Is it what you are looking for?

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-02-08 07:06

    I think you need smth like:

    Obj.setSide(Side.valueOf(zasAlloc.getM_buySellCode()));
    
    0 讨论(0)
提交回复
热议问题