如何重新枚举枚举的价值 [英] How do I reimplement valueof on enumeration

查看:112
本文介绍了如何重新枚举枚举的价值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要重新实现一些枚举的枚举方法,所以它们不再抛出异常,而是枚举中不存在值时返回null。

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.

我正在尝试基本的

@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?

推荐答案

你不能。你必须定义另一种不同的方法。 valueOf方法由编译器自动生成。

You can't. You'll have to define another, different method. The valueOf method is automatically generated by the compiler.

public static MyEnum permissiveValueOf(String name) {
    for (MyEnum e : values()) {
        if (e.name().equals(name)) {
            return e;
        }
    }
    return null;
}

这篇关于如何重新枚举枚举的价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆