Reputation: 3
Suppose I have an object Class<?> c
. Is it possible to create a generic list with c as the generic parameter?
So something like this:
Class<?> c = doSomething();
List<c> list = new ArrayList<c>();
Upvotes: 0
Views: 411
Reputation: 147164
For Class<? extend T> clazz
, List<T>
can be used for any instance created by clazz
. For Class<? super T> clazz
, List<T>
should only contain instance that are compatibly with clazz
.
For Class<?>
, List<Object>
is probably what you want. Any use of reflection, including Class
is usually a mistake.
Upvotes: 1
Reputation: 17597
No that is impossible - at least your grammar will not compile. However, you may try to learn generics in Java, and see whether that helps your specific case, as this may be a A-B problem.
For example, this works:
<T> int yourFunction(List<T> items) {
T item = items.get(0);
// play with the item of type T, yeah!
}
Upvotes: 1