从许多枚举的价值中找到枚举的最佳方法(Best way to find enum from value for many enums)
我有很多枚举。
我想为所有枚举添加一个通用方法,允许通过值查找枚举。 就像这样的事情:
public static T getEnumFromVal(String val) { for (T e : values()) { if (e.getVal().equals(val)) { return e; } } return null; }我可以让enum实现一个接口,但不幸的是我使用Java 6而且我不能声明一个静态方法:( ...
你有其他想法吗?
I have a lot of enum.
I would like to add a generic method for all enums allowing to find the enum by the value. Just with something like that :
public static T getEnumFromVal(String val) { for (T e : values()) { if (e.getVal().equals(val)) { return e; } } return null; }I could make the enum implements an interface, but unfortunately I am using Java 6 and I can not declare a static method :( ...
Do you have an other idea ?
最满意答案
public static <T extends Enum<T> & HasVal> getEnumFromVal(Class<T> enumClass, String val) { for (T e : enumClass.getEnumConstants()) { if (e.getVal().equals(val)) { return e; } } return null; }其中HasVal是定义getVal()方法的通用接口
public static <T extends Enum<T> & HasVal> getEnumFromVal(Class<T> enumClass, String val) { for (T e : enumClass.getEnumConstants()) { if (e.getVal().equals(val)) { return e; } } return null; }where HasVal is the common interface defining the getVal() method
更多推荐
发布评论