Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement enum with generics?

I have a generic interface like this:

interface A<T> {     T getValue(); } 

This interface has limited instances, hence it would be best to implement them as enum values. The problem is those instances have different type of values, so I tried the following approach but it does not compile:

public enum B implements A {     A1<String> {         @Override         public String getValue() {             return "value";         }     },     A2<Integer> {         @Override         public Integer getValue() {             return 0;         }     }; } 

Any idea about this?

like image 490
Zhao Yi Avatar asked Jul 15 '12 08:07

Zhao Yi


People also ask

How do you use generic enums?

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.

Can enum be used for generics Java?

Java enums will be enhanced with generics support and with the ability to add methods to individual items, a new JEP shows. Since both features can be delivered with the same code change, they are bundled together in the same JEP. The change only affects the Java compiler, and therefore no runtime changes are needed.

How are enums implemented?

Enums are statically created when the enum class is first loaded and are immutable. You must have a constructor in the enum class if you want to assign different values to your enum. After the constructor was finished you cannot change the enums value (immutable as said).

Can enum have static methods?

The enum class body can include methods and other fields. The compiler automatically adds some special methods when it creates an enum. For example, they have a static values method that returns an array containing all of the values of the enum in the order they are declared.


1 Answers

You can't. Java doesn't allow generic types on enum constants. They are allowed on enum types, though:

public enum B implements A<String> {   A1, A2; } 

What you could do in this case is either have an enum type for each generic type, or 'fake' having an enum by just making it a class:

public class B<T> implements A<T> {     public static final B<String> A1 = new B<String>();     public static final B<Integer> A2 = new B<Integer>();     private B() {}; } 

Unfortunately, they both have drawbacks.

like image 116
Jorn Avatar answered Sep 20 '22 22:09

Jorn