Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: generic enum in method parameter

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...

like image 996
Ed Michel Avatar asked Dec 01 '10 14:12

Ed Michel


People also ask

Can you use an enum as a parameter in Java?

Yes, you can pass enum constants to methods, but you shouldn't use the 'enum' keyword in the method declaration, just like you don't use the 'class' keyword in a method declaration.

Can you declare enum in method?

Declaration of enum in Java: Enum declaration can be done outside a Class or inside a Class but not inside a Method.

Can enums be generic Java?

The enum is a default subclass of the generic Enum<T> class, where T represents generic enum type. This is the common base class of all Java language enumeration types. The transformation from enum to a class is done by the Java compiler during compilation. This extension need not be stated explicitly in code.

Can enum be parameterized?

Enums can be parameterized.


1 Answers

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
like image 131
Sean Patrick Floyd Avatar answered Sep 21 '22 18:09

Sean Patrick Floyd