如何重新实现枚举的 valueof
我需要重新实现一些枚举的 enum.valueof 方法,以便它们不再抛出异常,而是在枚举中不存在值时简单地返回 null。
我正在尝试基本功能
@Override
public static <T extends Enum<T>> T valueOf(Class<T> enumType,
String name){
,但它不起作用,说我需要覆盖或实现超级类型。
我想我可以想出一个超级类,但我只是不确定如何将它们组合在一起。有什么想法吗?
I need to re-implement the enum.valueof method of a few of my enumerations so they no longer throw exceptions, instead they simply return null if a value doesn't exist in the enumeration.
I'm trying the basic
@Override
public static <T extends Enum<T>> T valueOf(Class<T> enumType,
String name){
but it's not working, saying I need to override or implement a super type.
I can come up with a super class I guess, but I'm just not sure how to put this together. Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
你不能。您必须定义另一种不同的方法。 valueOf 方法由编译器自动生成。
You can't. You'll have to define another, different method. The valueOf method is automatically generated by the compiler.
使用 Apache Commons Lang:
引用 EnumUtils.getEnum 的 Javadoc:
Use Apache Commons Lang:
Quote from the Javadoc for EnumUtils.getEnum:
该方法是否绝对有必要像枚举自动具有的方法一样调用
valueOf
?在我目前正在进行的项目中,我们有类似的方法,但我们对它们的称呼不同;例如,forName
:Is it absolutely necessary that the method is called
valueOf
like the method that enums have automatically? In the project that I'm currently working on we have similar methods, but we call them differently; for example,forName
:您不必覆盖 valueOf。这就是我所做的:
我必须将一些字符串“解析”为枚举,但它们与声明名称不匹配,因此我对
valueOf(String name)
进行了某种重新实现。这段代码已经过测试并且可以工作。
您可以使用类似:
它的输出将是:
希望它有帮助。
You don't have to override valueOf. Here's what I did:
I had to "parse" some strings to enums and they didn't match with their declaration names, so I did a sort of reimplementation of
valueOf(String name)
.This code is tested and works.
You can use like:
And it's output would be:
Hope it helps.
您可以考虑在枚举类中创建一个新的(不同名称,例如转换)静态方法。
You might consider creating a new (different name such as convert) static method in your enum classes.