设置基于字符串传入一个枚举值 [英] Setting an Enum value based on incoming String
本文介绍了设置基于字符串传入一个枚举值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一些它需要一个枚举setter方法。这些都是基于传入对象的属性。而不是写一堆的这些是有办法解决有硬code的方式说10种不同的case语句。会有创建可重用方法的方法是什么?
//端类声明
公众最终侧面枚举//我怎么初始化方
静态并排= Side.SELL; //默认//方法来设置对象
Obj.setSide(sideEnum(zasAlloc.getM_buySell code()));//如何我实现它
公共静态侧sideEnum(字符串buysell)
{ 如果(buysell.equalsIgnoreCase(S))
{
侧= Side.SELL; //默认
}
否则如果(buysell.equalsIgnoreCase(B))
{
侧= Side.BUY;
} 返回的一面; }
解决方案
最后我用一个简单的对象图:
私有静态HashMap的<弦乐,侧面> sideMap =新的HashMap<弦乐,侧面>(7);
静态的{
sideMap.put(B,Side.BUY);
sideMap.put(S,Side.SELL);
}
和简单地使用
Obj.setSide(sideMap.get(zasAlloc.getM_buySell code()));
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;
}
解决方案
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()));
这篇关于设置基于字符串传入一个枚举值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文