我如何创建一个泛型类型的实例?

我知道这个问题已经被问过,但是我还没有解决。

我想通过泛型创建一个类的实例。

我试过这个:

Class<VH>::getConstructor.call(parameter).newInstance() 

但是,我得到这个错误: I get this error for this method: Callable expects 2 arguments, but 1 were provided.

我也试过这个方法:

 inline fun <reified VH> create(): VH { return VH::class.java.newInstance() } 

但是,我无法调用它,因为我不能使用通用类型作为通用类型。

这种方法也不起作用:

 fun <VH> generateClass(type: Class<VH>): VH { return type.newInstance() } 

就像我这样调用它时: generateClass<VH>(Class<VH>::class.java)我得到这个错误: Only classes are allowed on the left handside of a class literal

我的问题简而言之 :如何从泛型创建一个类的实例?

提前致谢

你不能。 除非通用类型被通用化,否则它将在运行时消失,使您无法创建实例。

你的实例化函数create()例子是有效的,但是在编译期间必须解析一个实体类型,所以标准的泛型类型不能作为实体类型输入。

具体化“类生成”的例子:

 inline fun <reified VH : Any> generateClass(): RecyclerView.Adapter { return object : RecyclerView.Adapter<VH>() { override fun onBindViewHolder(VH holder, int position) { // Do implementation... } ... } } 

答案是使用反射和一个泛化的泛型类型。

首先,确保以VH为参数的方法是一个内联函数。 一旦你有一个通用类型的通用版本,你可以得到它的类名。

一旦你有它的类名,你可以使用反射来实例化它。

这是你如何得到班级的名字:

 inline fun <reified VH: CustomClass> myMethod() { //Make sure you use the qualifiedName otherwise the reflective call won't find the class val className VH::class.qualifiedName!! } 

这是你如何实例化类:

Class.forName(className).newInstance(constructorData) as VH

注意 :如果这个类是一个内部类,那么你将得到一个classnotfoundexception,除非你用一个$符号替换内部类的名称之前的点。

这是一个例子:

com.example.package.outerClass.innnerClass – 这将抛出classnotfoundexception

com.example.package.outerClass$innnerClass – 这将成功找到这个类

更新:

你可以使用避免反射的另一个解决方案是使用泛化类型的构造函数。

以下是你如何得到它的构造函数:

 inline fun <reified VH: CustomClass> myMethod() { val customClassConstructor = VH::class.constructors.first() } 

这是如何使用其构造函数实例化泛化泛型:

 customClassConstructor.call(constructorData)