背景
我对Java泛型的理解是它完全是一个编译时特性(主要关注类型安全检查)。任何泛型类的类型信息在运行时都会丢失(类型擦除)。
尽管如此,我看到许多框架似乎也在运行时利用类型信息。例如,Google Guice Providers。Guice Provider可以在运行时实例化并提供其泛型类型的新实例。
class Container
{
@Inject
public Container(Provider<Content> contentProvider)
{
//This works at Runtime... but How ???
//When type's are not even preserved at runtime, how does the Provider knows it has to instantiate an object of type 'Content'
Content content = contentProvider.get();
}
}
问题
在运行时,是否还保留与通用类型相关的信息?如果是,是什么?如果不是,那么像 Google Guice 这样的库是如何在内部操作的(上面的例子)?
泛型除了编译时安全性以外,还有更多的用途吗?比如说,在确保编译时安全性的情况下,是否有其他场景可以使用泛型并获得优势?