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 ?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With