Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Generic accepting only enum types

Assuming that I have a basic enum like:

public enum Color { Red, Green, Blue}

How can one write a generic class which only accepts "enum classes" so that a concrete instantiation of that generic class might look like MyClass<Color>?

Edit:

What a actually want to do is to write a generic abstract class containing a function returning all enum "entries" as list:

public abstract class EnumListBean<E extends Enum<E>> {

    public List<E> getEnumList() {
        return Arrays.asList(E.values());
    }

}

While Day.values() is available E.values() is not. What i am doing wrong here?

like image 619
Sebastian Hoffmann Avatar asked Jul 15 '12 11:07

Sebastian Hoffmann


People also ask

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.

Can enums be generic?

enum is treated as a special type and Microsoft haven't implemented this (yet). However, it is possible to use enums in generics. The MSDN article for Enum gives the following type definition for the class Enum .

Can enums have different types?

Enums have their own data type and each enum is essentially a new data type. This is where one of their their biggest powers lie - they can be strongly type checked at compile time. I have added further values to demonstrate the resultant versatility.

Is enum allowed in switch case?

Yes, You can use Enum in Switch case statement in Java like int primitive. If you are familiar with enum int pattern, where integers represent enum values prior to Java 5 then you already knows how to use the Switch case with Enum.


1 Answers

public class EnumAcceptor<E extends Enum<E>> {
    ...
}

Use E as a type inside your class.

like image 122
Istvan Devai Avatar answered Sep 20 '22 04:09

Istvan Devai