在 kotlin 中创建泛型类的新实例的正确方法是什么? [英] What is the proper way to create new instance of generic class in kotlin?
问题描述
我使用以下初始化:
val entityClass = javaClass<Class<T>>()
var entity = entityClass.newInstance().newInstance()
但它是错误的并导致 java.lang.Class.newInstance(Class.java:1208)
推荐答案
如果让 IntelliJ 添加显式类型信息,您会看到 entityClass
实际上是 Class
Class
实例,然后创建了一个 T
实例,但这无论如何都是不可能的,因为关于 T
的通用信息code> 在运行时丢失.除此之外,您不能直接实例化类对象.
If you let IntelliJ add explicit type information, you see that entityClass
is actually of type Class<Class<String>>
. I'm not sure if that's what you want. In line 2 you are first creating an instance of Class<T>
and then one of T
but that's not possible anyway, because the generic information about T
is lost at runtime. Apart from that you can't instantiate class objects directly.
一种可能的解决方案是将 Class
类型的参数添加到您的函数或类中,并使用它来实例化这样的对象.
One possible solution would be to add a parameter of type Class<T>
to your function or class and use it to instantiate objects like this.
fun <T> foo(entityClass: Class<T>) {
var entity: T = entityClass.newInstance()
}
fun test() {
foo(Object::class.java)
}
但实际上有一个更优雅的解决方案,而不使用反射.定义一个方法类型的参数() ->T
并使用构造函数引用.这是我关于构造函数引用的相关问题,代码如下:
But there's actually a more elegant solution without the use of reflection. Define a parameter of method type () -> T
and use constructor references. Here's my related question about constructor references and here's the code:
fun <T> foo2(factory: () -> T) {
var entity: T = factory()
}
fun test() {
foo2(::Object)
}
这篇关于在 kotlin 中创建泛型类的新实例的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!