枚举共享静态查找方法 [英] Enums shared static look-up method
问题描述
我有以下枚举:
public enum MyEnum{
A(10, "First"), //
B(20, "Second"), //
C(35, "Other options");
private Integer code;
private String description;
private MyEnum(Integer code, String description) {
this.code = code;
this.description = description;
}
public Integer getCode() {
return code;
}
public String getDescription() {
return description;
}
public static MyEnum getValueOf(Integer code) {
for (MyEnum e : MyEnum.values()) {
if (e.getCode().equals(code)) {
return e;
}
}
throw new IllegalArgumentException("No enum const " + MyEnum.class.getName() + " for code \'" + code
+ "\'");
}
}
哪个工作正常。 getValueOf
-method存在是因为当与外部合作伙伴进行通信时,我们只获取代码(他们选择)映射到。我需要描述,因为我需要在GUI中显示一个有意义的短语。
Which works fine. The getValueOf
-method exists because when communicating with an external partner, we only get the code (they chose) to map to. I need the description because I need to show a meaningfull phrase in the GUI.
但是我现在有一些类似的枚举类。所有人都有自己的代码描述,并且它们需要相同的查找功能。
我希望 getValueOf
-method是通用的,所以我不需要支持基于相同方法的30多个不同的枚举。
But I now have a number of similar enum classes. All having their own code & description, and they need the same lookup functionality.
I wanted the getValueOf
-method to be generic so I don't need to support 30+ different enums for basically the same method.
为了解决这个问题,我想使一个抽象类定义这个方法并实现一些常见的逻辑,但这是不可能的,因为我不能扩展枚举
。
To solve this I wanted to make an abstract class to define this method and implement some of the common logic but this is impossible because I can't extend Enum
.
然后,我尝试使用以下方法创建一个Utility类:
Then I tried to make a Utility class with the following method:
public static <T extends Enum<T>> T getValueOf(Enum<T> type, Integer code) {...}
但是枚举与枚举令人困惑,我不明白如何使这个工作。
But generics with Enums are confusing and I don't understand how to get this working.
基本上我想知道的是:什么是一个很好的方法来定义一个常见的实用程序到枚举?
Basically what I want to know is: What is a good approach to define a common utility to an enum?
推荐答案
您需要将实际的枚举类对象作为参数传递给您的方法。然后,您可以使用 Class.getEnumConstants()
获取枚举值。
You need to pass the actual enum class object as a parameter to your method. Then you can get the enum values using Class.getEnumConstants()
.
为了能够访问 getCode()
在实例上,您应该在界面中定义它,并使所有的枚举类型实现该接口:
In order to be able to access getCode()
on the instances, you should define it in an interface and make all your enum types implement that interface:
interface Encodable {
Integer getCode();
}
public static <T extends Enum<T> & Encodable> T getValueOf(Class<T> enumClass, Integer code) {
for (T e : enumClass.getEnumConstants()) {
if (e.getCode().equals(code)) {
return e;
}
}
throw new IllegalArgumentException("No enum const " + enumClass.getName() + " for code \'" + code
+ "\'");
}
...
public enum MyEnum implements Encodable {
...
}
MyEnum e = getValueOf(MyEnum.class, 10);
这篇关于枚举共享静态查找方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!