java 如何在java中通过2个参数返回枚举值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12829766/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to return enum value by 2 parameters in java
提问by Constantine Gladky
I have such enum class in java
我在java中有这样的枚举类
public enum MockTypes
{
// Atlantis mocks
ATLANTIS_VERIFY("ATLANTIS", "verify"),
ATLANTIS_CREATE_RECORD("ATLANTIS", "createRecord"),
...
private String m_adaptor;
private String m_step;
private MockTypes( String adaptor, String step)
{
m_adaptor = adaptor;
m_step = step;
}
public String getAdaptor()
{
return m_adaptor;
}
public String getStep()
{
return m_step;
}
I have to implement method that returns enum value by adaptor and step parameter.
我必须实现通过适配器和步骤参数返回枚举值的方法。
public MockTypes getMockTypeByName(String adaptor, String step)
but I have no idea how. Could someone help me?
但我不知道如何。有人可以帮助我吗?
回答by Eng.Fouad
public MockTypes getMockTypeByName(String adaptor, String step)
{
for(MockTypes m : MockTypes.values())
{
if(m.getAdaptor().equals(adaptor) &&
m.getStep().equals(step)) return m;
}
return null;
}
回答by Louis Wasserman
If you want a "constant-time" solution that doesn't involve looking up values, your best option is to initialize a constant Map
in a static block in the MockType
class.
如果您想要一个不涉及查找值的“常量时间”解决方案,最好的选择是Map
在MockType
类的静态块中初始化一个常量。
If you're up for using Guava, it'll actually be relatively pleasant:
如果您准备使用Guava,它实际上会相对令人愉快:
public enum MockType {
...
private static final ImmutableTable<String, String, MockType> LOOKUP_TABLE;
static {
ImmutableTable.Builder<String, String, MockType> builder =
ImmutableTable.builder();
for (MockType mockType : MockType.values()) {
builder.put(mockType.getAdaptor(), mockType.getStep(), mockType);
}
LOOKUP_TABLE = builder.build();
}
public static MockType getMockType(String adaptor, String step) {
return LOOKUP_TABLE.get(adaptor, step);
}
}
(Disclosure: I contribute to Guava.)
(披露:我为番石榴做出了贡献。)
The alternative is going to be relatively similar -- construct a Map<String, Map<String, LookupType>>
in a static block, and do lookups from there -- though it's going to require somewhat more work.
替代方案将相对相似——Map<String, Map<String, LookupType>>
在静态块中构造一个,并从那里进行查找——尽管它需要更多的工作。
回答by rid
You can use enum
's values()
method to obtain a list of all the defined values. You can then loop through this list and find the values you're interested in that match the ones sent as parameters to the method.
您可以使用enum
的values()
方法来获取所有已定义值的列表。然后,您可以遍历此列表并找到您感兴趣的值,这些值与作为参数发送给方法的值相匹配。