写入方法,可获取/返回任何枚举的枚举常量 [英] Write method that takes/returns enum constants of any enum

查看:227
本文介绍了写入方法,可获取/返回任何枚举的枚举常量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我存储配置枚举时,只要将它绑定到特定的枚举类型 MyEnum

When I store a configuration enum, this is easy as long as it is type-bound to, say, a special enum type MyEnum:

void storeMyEnumValue(MyEnum value) {
    String valueString = value.name();
    // Store valueString somewhere
}

MyEnum loadMyEnumValue(MyEnum fallbackValue) {
    // Load valueString from somewhere
    try {
        return MyEnum.valueOf(valueString);
    } catch (Exception e) {
        return fallbackValue;
    }
}

但是如果我想将其归纳并得到一个

store / load 方法的集合?

But what if I want to generalize that and have a set of store/load methods for any type of enum?

void storeAnyEnumValue(??? value) {
    // The same as before
}

??? loadAnyEnumValue(??? defaultValue) {
    // The same as before
}

因此,您可以看到,问题主要是通常如何处理枚举常量类型的对象。

So as you can see, the question is mainly how to handle "objects of the type enum constant" in general.

推荐答案

对于store方法,您可以仅使用 Enum<?> 的实例。

For the store method, you can just use an instance of Enum<?>. There is no advantage to a type variable here.

void storeAnyEnumValue(Enum<?> value) {
    // The same as before
}

对于load方法,您希望返回类型为与 defaultValue 具有相同的类型,因此这里确实需要类型变量:

For the load method, you want the return type to be of the same type as the defaultValue, so you do need a type variable here:

<E extends Enum<E>> E loadAnyEnumValue(E defaultValue) {
    // The same as before
}

这篇关于写入方法,可获取/返回任何枚举的枚举常量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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