Java: generic enum in method parameter

48,366

Solution 1

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:

Solution 2

You can also do it this way:

public class Bar {
    public Bar(Enum<?> e){}
}

Every enumeration extends Enum. Then you can use this if you need the enum constants:

e.getDeclaringClass().getEnumConstants()

Solution 3

public class bar {
    public <E extends Enum<E>> void bar(E enumObject);
}

The bar method can now receive any kind of enum.

Share:
48,366
Ed Michel
Author by

Ed Michel

Updated on September 24, 2020

Comments

  • Ed Michel
    Ed Michel over 3 years

    Correspondig the following question:

    Java: Enum parameter in method

    I would like to know, how can I format the code to require enums generically.

    Foo.java

    public enum Foo { 
        a(1), b(2);
    }
    

    Bar.java

    public class Bar {
        public Bar(generic enum);
    }
    

    Later on I'll have more enum classes like "foo", but you can still create bar containing any kind of enum class. I have "jdk1.6.0_20" by the way...

  • Roboprog
    Roboprog over 6 years
    Thank you for that example, as nonsensical as the syntax is - which I am reading as "PLACEHOLDER extends Enum of PLACEHOLDER" (vs just "PLACEHOLDER extends SuperType" for non-enums)
  • cdgraham
    cdgraham about 2 years
    While this isn't using generics like OP asked, this answer will likely provide a simple solution to many people's problems without needing a generic to begin with!