简体   繁体   English

Java Generics Type Argument as Variable可能吗?

[英]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. 就像@Jesper所说,你正试图跨越编译时和运行时范围。

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. 首先,要了解Java泛型是一个严格的编译时功能 - 一旦你的java源代码编译成字节代码,你在源代码中看到的'泛型'就不见了。 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 . @ Neal Gafter博客发表了关于Java Generics未经具体设计的原因的讨论。

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! 编译器不能为其泛型类型提供动态值,因为在运行时,您可以将String换成另一种类型,突然它不应该编译,但它已经太晚了,因为它正在运行! 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<?> > 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. 这保证了类型可以用作Collection,因为该类型必须是Collection的子类。

See here if you want to read up on this topic. 如果您想阅读此主题, 请参阅此处

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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