Java: generic enum in method parameter

See the methods in EnumSet for reference, e.g.

public static <E extends Enum<E>> EnumSet<E> of(E e)

(This method returns an EnumSet with one element from a given Enum element e)

So the generic bounds you need are: <E extends Enum<E>>


Actually, you will probably make Bar itself generic:

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

    private final E item;

    public E getItem(){
        return item;
    }

    public Bar(final E item){
        this.item = item;
    }
}

You may also add a factory method like from, with etc.

public static <E2 extends Enum<E2>> Bar<E2> with(E2 item){
    return new Bar<E2>(item);
}

That way, in client code you only have to write the generic signature once:

// e.g. this simple version
Bar<MyEnum> bar = Bar.with(MyEnum.SOME_INSTANCE);
// instead of the more verbose version:
Bar<MyEnum> bar = new Bar<MyEnum>(MyEnum.SOME_INSTANCE);

Reference:

  • Java Tutorial – Learning the Java Language
    • Classes and Objects > Enum Types
    • Generics

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)