从许多枚举的价值中找到枚举的最佳方法(Best way to find enum from value for many enums)

编程入门 行业动态 更新时间:2024-10-25 15:20:24
从许多枚举的价值中找到枚举的最佳方法(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

更多推荐

本文发布于:2023-07-27 17:45:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1293559.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:价值   方法   中找到   enums   find

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!