I have a utility method that creates a one-element list out of some object:
public static final <T> List<T> list(T t) {
final List<T> rv = new ArrayList<>();
rv.add(t);
return rv;
}
I also have a method that accepts an argument of type List<Class<?>>
. So I have to create an object of that type. Here's what I try to do:
final Class<?> aClass = Integer.class;
final List<Class<?>> trivialListOfClasses = list(aClass);
… this fails with:
[javac] /some/path/Foo.java:41: error: incompatible types
[javac] final List<Class<?>> trivialListOfClasses = list(aClass);
[javac] ^
[javac] required: List<Class<?>>
[javac] found: List<Class<CAP#1>>
[javac] where CAP#1 is a fresh type-variable:
[javac] CAP#1 extends Object from capture of ?
[javac] 1 error
What's the proper way to accomplish the above? I understand the part about Java generics being invariant but what exactly is going on here?