简体   繁体   中英

Java Generics Type Argument as Variable possible?

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 .

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<?> > 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM