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 say 10 different case statements. Would there be a way to create a reusable method?
//Side class declared as
public final enum Side
//How I initialise side
static Side side = Side.SELL;//default
//method to set object
Obj.setSide(sideEnum(zasAlloc.getM_buySellCode()));
//How I am implementing it
public static Side sideEnum(String buysell)
{
if(buysell.equalsIgnoreCase("S"))
{
side = Side.SELL; //default
}
else if(buysell.equalsIgnoreCase("B"))
{
side = Side.BUY;
}
return side;
}
Use a Switch statement. The simplest way to convert enum values into string representation is by using a switch statement.
You can create Enum from String by using Enum. valueOf() method. valueOf() is a static method that is added on every Enum class during compile-time and it's implicitly available to all Enum along with values(), name(), and cardinal() methods.
You can assign different values to enum member. A change in the default value of an enum member will automatically assign incremental values to the other members sequentially.
Given those limitations, the enum value alone is not suitable for human-readable strings or non-string values. In this tutorial, we'll use the enum features as a Java class to attach the values we want.
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.
Enums have valueOf() method that can be used to convert from String. Is it what you are looking for?
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()));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With