Wil*_*ill 11 java string enums attributes
我有许多setter方法,它们采用枚举.这些基于传入对象属性.而不是写一堆这些是有一种方法来必须硬编码说10个不同的案例陈述.有没有办法创建一个可重用的方法?
//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;
}
Run Code Online (Sandbox Code Playgroud)
jjn*_*guy 25
您可以在您的实现中实现该功能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;
}
}
Run Code Online (Sandbox Code Playgroud)
如果无法编辑,也可以将其作为辅助静态方法Side
.
public static Side fromString(String from) {
for (Side s: Side.values()) {
if (s.toString().startsWith(from)) {
return s;
}
}
throw new IllegalArgumentException( from );
}
Run Code Online (Sandbox Code Playgroud)
上面的方法假设您的字符串对应于您枚举的名称.
我最终使用了一个简单的对象映射:
private static HashMap<String, Side> sideMap = new HashMap<String, Side>(7);
static{
sideMap.put("B", Side.BUY);
sideMap.put("S", Side.SELL);
}
Run Code Online (Sandbox Code Playgroud)
并简单地使用
Obj.setSide(sideMap.get(zasAlloc.getM_buySellCode()));
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
21412 次 |
最近记录: |