Reputation: 4868
I have an interface
:
public interface NamedEnum {
String getName();
}
An enum
which implements the interface
:
public enum MyEnum implements NamedEnum {
MYVALUE1("My value one"),
MYVALUE2("My value two");
private String name;
private MyEnum(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
A method which doesn't compile:
public static Map<Integer,String> wrong(Enum<? extends NamedEnum> value) {
Map<Integer,String> result = new LinkedHashMap<Integer, String>();
for (Enum<? extends NamedEnum> val : value.values())
result.put(val.ordinal(), val.getName());
return result;
}
Two errors:
The method values() is undefined for the type Enum<capture#1-of ? extends NamedEnum>
The method getName() is undefined for the type Enum<capture#3-of ? extends NamedEnum>
I can't figure out how the method above can accept an enum
which implements the interface
.
Upvotes: 4
Views: 2447
Reputation: 30723
While I agree with the solution suggested by Andy, I think you may also want to look at the problem differently.
IIUC, you are looking for a way to get the value returned by getName() based on the enum's ordinal. In other words, you're looking for a mapping such as this:
If that's indeed the case then how about using the array of enum values directly (the array is indexed by the enum ordinal values). For instance:
NamedEnum[] arr = MyEnum.values();
System.out.println(arr[0].getName()); // Output: "My value one"
System.out.println(arr[1].getName()); // Output: "My value two"
Note that the arr
variable can be assigned from different enums (as long as they implement the NamedEnum
interface). For instance, if you have this other enum defined in your program:
public enum MyOtherEnum implements NamedEnum {
MYVALUE3("My other value three"),
MYVALUE4("My other value four");
private String name;
private MyOtherEnum(String name) {
this.name = name;
}
@Override
public String getName() {
return name;
}
}
Then the following is a valid main() method:
public static void main(String[] args) {
NamedEnum[] arr = MyEnum.values();
System.out.println(arr[0].getName());
System.out.println(arr[1].getName());
arr = MyOtherEnum.values();
System.out.println(arr[0].getName());
System.out.println(arr[1].getName());
}
The output, as expected is:
My value one
My value two
My other value three
My other value four
Hope that helps.
Upvotes: 3
Reputation: 140309
Define a type variable with an intersection type:
public static <E extends Enum<E> & NamedEnum> Map<Integer,String> wrong(E value) {
But note that this is passing an element of the enum, not the enum class itself. You might want to use:
public static <E extends Enum<E> & NamedEnum> Map<Integer,String> wrong(Class<E> clazz) {
and then use clazz.getEnumConstants()
to get the values to iterate over:
for (E val : clazz.getEnumConstants())
Alternatively, you can use value.getDeclaringClass().getEnumConstants()
.
Upvotes: 9