4

is it possible to give a type argument to a generic class via a variable ?:

private static final Class clazz = String.class;

ArrayList<clazz> list = new ArrayList<>();

In this example i get an compiler error. So why is that not possible ?

2
  • 4
    You are mixing compile-time and runtime concepts. Generics are for type checking at compile-time. They are not useful if you don't know the type before runtime. You can't use the value of a variable, which is something that you'll only know at runtime, as a type parameter. Commented Feb 18, 2016 at 13:59
  • No, since the type argument is infact a type not a class object per say. Commented Feb 18, 2016 at 14:00

2 Answers 2

4

Like @Jesper said, you're trying to cross compile-time and run-time scopes.

First of all, understand that Java generics are a strictly compile-time feature - that is once your java source is compile to byte code, the 'generics' as you see them in your source are gone. I'd suggest reading up on type erasure for more on the subject.

So what does the compiler do with generics? It verifies that the casts and operations are safe, then automatically inserts various operations into your compiled code for you. Here is where the problem lies - you're asking the compiler to perform operations based on a parameter supplied at run-time. The gist is that since the compiler does not have access to the run-time values, it cannot compile the generics and an error occurs.

Great discussion on why Java Generics were designed without reification found @ Neal Gafter's Blog.

Sign up to request clarification or add additional context in comments.

Comments

0

The compiler cannot okay a dynamic value for its generic type, because at runtime you could swap String for another type and suddenly it shouldn't compile, but it's already too late because it's running! The proper way to do this is to use interfaces or abstract classes to indicate that a given type must be a subclass of that.

An example might be ArrayList< ? extends Collection<?> >. This guarantees that the type can be used as a Collection since that type must be a subclass of Collection.

See here if you want to read up on this topic.

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.