我知道这个问题以前有人问过,但我还没有能够解决它。
我正在尝试通过泛型类型创建类的实例。
我试过这个:
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
.
简而言之,我的问题:如何从泛型类型创建类的实例?
提前致谢
答案是使用反射和具体的泛型类型。
首先,确保以 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
- 这将抛出类不发现异常
com.example.package.outerClass$innnerClass
- 这将成功找到类
更新:
可以使用的另一种避免反射的解决方案是使用已确定的泛型类型的构造函数。
以下是获取其构造函数的方法:
inline fun <reified VH: CustomClass> myMethod() {
val customClassConstructor = VH::class.constructors.first()
}
以下是使用构造函数实例化化泛型类型的方式:
customClassConstructor.call(constructorData)
你不能。除非泛型类型被化,否则它将在运行时消失,从而使您无法创建实例。
您的化函数示例create()
工作,但必须在编译期间解析化类型,因此无法将标准泛型类型作为化类型输入。
具体化的"类生成"示例:
inline fun <reified VH : Any> generateClass(): RecyclerView.Adapter {
return object : RecyclerView.Adapter<VH>() {
override fun onBindViewHolder(VH holder, int position) {
// Do implementation...
}
...
}
}