简体   繁体   中英

How to return an enum from a class using generic enum type in Java

I've got a class that I'd like to use a generic enum type in, like this:

public class PageField<E extends Enum<E>>{
}

It seems like I should be able to have a getter method inside that class that then could return an enum <E> instance, like this:

public E getSelectedValue() {
    String value = getValueFromElement(this.id);
    return E.valueOf(value);
}

But i keep getting the following error:

Inferred type 'java.lang.Object' for type parameter 'T' is not within its bound; should extend 'java.lang.Enum'

What am I doing wrong? Is this possible?

You cannot call the method valueOf on E : it is not an object, it is just a type parameter.

What you should do is pass the Class of the current enum type parameter so that you can use it to retrieve the enum value:

public class PageField<E extends Enum<E>>{

    private Class<E> enumClass;

    public PageField(Class<E> enumClass) {
        this.enumClass = enumClass;
    }

    public E getSelectedValue() {
        String value = getValueFromElement(this.id);
        return Enum.valueOf(enumClass, value);
    }

}

Unfortunately, there is no way to retrieve the class of the type E because of type erasure, so you need to give it explicitely.

The actual error message from the compiler is

Error:(6, 17) java: method valueOf in class java.lang.Enum<E> cannot be applied to given types;
  required: java.lang.Class<T>,java.lang.String
  found: java.lang.String
  reason: cannot infer type-variable(s) T
    (actual and formal argument lists differ in length)

Since the actual type of the enum is unknown, calling valueOf(String) is impossible, and the compiler thinks you're trying to call

public static <T extends Enum<T>> T valueOf(Class<T> enumType,
                                            String name)

That's actuall the method you should call. But that means that your generic class needs to have a reference to the Class of the enum. Just as EnumSet does, for example. See the answer of @Tunaki for an example.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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