0

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>();
1
  • 4
    If you could do this, it wouldn't be useful. Generic types are only useful before compiling. If you could do this, you couldn't do anything with it you couldn't do with List<?>. Commented Jan 20, 2021 at 14:18

2 Answers 2

1

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!
    }
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.