简体   繁体   English

写方法,该方法按类返回/返回任何枚举的枚举常量

[英]Write method that takes/returns enum constants of any enum BY CLASS

I am getting the generics mixed up again... 我又把仿制药弄混了...

With the help of this question , I've written methods to store and retrieve Enum values, not tied to a specific enum class: 这个问题的帮助下,我编写了一些方法来存储和检索Enum值,而不是绑定到特定的enum类:

public static void storeEnum(Enum<?> enumValue) {
    // Store it somehow
}

public static <E extends Enum<E>> E getEnum(E defaultValue) {
    String valueString = // get it somehow
    try {
        return (E) Enum.valueOf(defaultValue.getDeclaringClass(), valueString);
    } catch (Exception e) {
        return defaultValue;
    }
}

But now I do not want to have any default value any more, I want to have null in case of no luck! 但是现在我不想再有任何默认值了,如果运气不好,我想将其设置为null

First attempt: 第一次尝试:

public static <E extends Enum<E>> E getEnum(Class<? extends Enum> enumClass) {
    String valueString = // get it somehow
    try {
        return (E) Enum.valueOf(enumClass, valueString);
    } catch (Exception e) {
        return null;
    }
}

This compiles, but when I want to get a stored MyCoolEnum , the line MyCoolEnum mci = getEnum(MyCoolEnum.class); 这样可以编译,但是当我要获取存储的MyCoolEnum ,行MyCoolEnum mci = getEnum(MyCoolEnum.class); breaks the (Maven) compile run: incompatible types: inference variable E has incompatible upper bounds java.lang.Enum<E>,MyCoolEnum . 中断(Maven)编译运行: incompatible types: inference variable E has incompatible upper bounds java.lang.Enum<E>,MyCoolEnum

Of course, this comes from the ? 当然,这来自于? . But how can I infer the type from the class? 但是如何从类中推断类型?

  • (Class<E extends Enum> enumClass) is not valid. (Class<E extends Enum> enumClass)无效。
  • (Class<Enum<E>> enumClass) breaks the valueOf ( The inferred type Enum<E> is not a valid substitute for the bounded parameter <T extends Enum<T>> ). (Class<Enum<E>> enumClass)打破了valueOfThe inferred type Enum<E> is not a valid substitute for the bounded parameter <T extends Enum<T>> )。

I can not reproduce your first error, but as an alternative, you should be able to use Class<E> ie: 我无法重现您的第一个错误,但是作为替代,您应该可以使用Class<E>即:

public static <E extends Enum<E>> E getEnum(Class<E> enumClass) {
    String valueString = // get it somehow
    try {
        return Enum.valueOf(enumClass, valueString);
    } catch (Exception e) {
        return null;
    }
}

(Note that you can also drop the cast) (请注意,您也可以删除演员表)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM