root
root

Reputation: 3

Java - Create generic list with class Object as generic parameter?

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

Answers (2)

Tom Hawtin - tackline
Tom Hawtin - tackline

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

ch271828n
ch271828n

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

Related Questions