I want to pass a list of enum classes to a method, where all of the enums implement a common interface, and have the method return one of the enum values.
Looking at Java Generics Wildcarding With Multiple Classes, it seems that
public class Main
{
interface Foo {}
enum First implements Foo {
A, B, C;
}
enum Second implements Foo {
X, Y, Z;
}
interface Bar {}
enum Third implements Bar {
M, N, P;
}
enum Fourth implements Bar {
A, X, Z;
}
public static <I, T extends Enum<?> & I>
I enumVarArgs(Class<? extends T>... classes)
{
// Do stuff and return some instance of T
return null;
}
public static void main(String[] args) {
Foo foo = enumVarArgs(First.class,
Second.class);
Bar bar = enumVarArgs(Third.class,
Fourth.class);
}
}
should do what I want. However, this fails to compile under Java 10:
[ERROR] /me/test/src/main/java/test/Main.java:[17,42] error: unexpected type
required: class
found: type parameter I
where I,T are type-variables:
I extends Object declared in method <I,T>enumVarArgs(Class<? extends T>...)
T extends Enum<?>,I declared in method <I,T>enumVarArgs(Class<? extends T>...)
[INFO] 1 error
From the error message, I am guessing that Java wants me to do something like T extends Enum<?> & Serializable
, where I pass an actual interface, rather than a type parameter. However, I need the API to be general so that I
remains a generic parameter.
Is there a syntax that makes this work?
If it matters, we are using Java 10.