Reputation: 565
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 ?
Upvotes: 4
Views: 70
Reputation: 5226
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.
Upvotes: 4
Reputation: 5780
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.
Upvotes: 0