本文介绍了使用反射在Java中创建通用参数化类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 如何使用反射在Java中创建泛型参数化类? 我有 public class SomeClass< T> { public SomeClass< T>(){} } 我尝试了 Class c = Class.forName(SomeClass); 但是找不到一个语法来让我得到一个适当类型的实例,比如 SomeType instance =(SomeType)Class.forName(SomeClass< SomeType>)。createInstance(); 所以,我怎么能这样做? List< Integer> 和 List< String> 在运行时被视为相同类型)。因为反射本质上是一个运行时功能,所以类型参数根本不被使用或涉及。 换句话说,你只能实例化原始类型( SomeClass ,而不是 SomeClass< T> )。然后您必须手动将该类型转换为通用版本(并生成未经检查的警告)。 How can I use reflection to create a generic parameterized class in Java?I have public class SomeClass<T> { public SomeClass<T>() { }}and I need an instance of it.I've tried variations ofClass c = Class.forName("SomeClass");but could not find a syntax that would allow me to get an appropriately typed instance, like, saySomeType instance = (SomeType)Class.forName("SomeClass<SomeType>").createInstance();So, how could I go about doing this? 解决方案 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). 这篇关于使用反射在Java中创建通用参数化类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
09-14 07:53