Use reflection to create a generic parameterized class in Java

旧街凉风 提交于 2019-11-28 11:15:20

Java uses erasure-based generics (i.e., the type parameters are erased at runtime—for example, List<Integer> and List<String> are treated as the same type at runtime). Since reflection is inherently a runtime feature, the type parameters are not used or involved at all.

In other words, you can only instantiate the raw type (SomeClass, not SomeClass<T>) when you're using reflection. You will then have to manually cast the type to the generic version (and generate an unchecked warning).

See/search for "Type erasure". Generics are for compile time and they are not availble at runtime so what you are trying is not possible. You need to use the raw type for reflection

Because of type erasure, at runtime SomeClass is all there is left of SomeClass<SomeType>.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!