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
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()));
Enums have valueOf() method that can be used to convert from String. Is it what you are looking for?
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.
I think you need smth like:
Obj.setSide(Side.valueOf(zasAlloc.getM_buySellCode()));