Reputation: 476
Given the following class:
...
Class<? extends Enum<?>> enumType;
public MyClass(Class<? extends Enum<?>> enumType) {
super();
this.enumType=enumType;
...
How do i define a method that returns an Enum of the "enumType" class?
I need something like:
public enumType getValue(){
...
}
,but this doesn't work ..
Upvotes: 0
Views: 93
Reputation: 206996
Use a type parameter instead of a wildcard. For example:
class MyClass<T extends Enum<T>> {
private Class<T> enumType;
public MyClass(Class<T> enumType) {
this.enumType = enumType;
}
public T getValue() {
// ...
}
}
edit In response to your comment, here's a method that lists all constants of an arbitrary enum
:
public <E extends Enum<E>> void showEnumValues(Class<E> e) {
for (E value : e.getEnumConstants())
System.out.println(value);
}
}
Upvotes: 7
Reputation: 77226
You have to actually specify a variable inside your generic, not just use wildcards everywhere. Then it's just like this:
public class MyClass<E extends EnumType<E>> {
Class<E> enumType;
E value;
public MyClass(Class<E> enumType) {
this.enumType = enumType;
}
public E getValue() {
return value;
}
}
Upvotes: 3