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?
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.
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 .
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.
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.
public class EnumAcceptor<E extends Enum<E>> {
...
}
Use E as a type inside your class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With