在kotlin中创建新的泛型类实例的正确方法是什么? [英] What is the proper way to create new instance of generic class in kotlin?

查看:209
本文介绍了在kotlin中创建新的泛型类实例的正确方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用以下初始化:

  val entityClass = javaClass< Class< T>>()
var entity = entityClass.newInstance()。newInstance()

但它是错误的并且导致 IllegalAccessException on java.lang.Class.newInstance(Class.java:1208)

entityClass 实际上是类型 Class< c $ c>类<字符串>> 。我不确定这是你想要的。在第2行中,您首先创建了一个 Class 实例,然后是 T 中的一个,但无论如何这是不可能的,因为有关 T 的通用信息在运行时会丢失。除此之外,您不能直接实例化类对象。



解决方案



一种可能的解决方案是添加一个类型为 Class 的参数添加到您的函数或类中,并用它来实例化这样的对象。

  fun< T> foo(entityClass:Class< T>){
var entity:T = entityClass.newInstance()
}

fun test(){
foo(Object: :class.java)
}

但实际上有一个更优雅的解决方案,反射。定义方法类型的参数() - > T 并使用构造函数引用。 这里是我的相关问题关于构造函数的参考,这里是代码:

  fun< T> foo2(factory:() - > T){
var entity:T = factory()
}

fun test(){
foo2对象)
}


I use following initialization:

val entityClass = javaClass<Class<T>>()
var entity = entityClass.newInstance().newInstance()

but it's wrong and causes IllegalAccessException on java.lang.Class.newInstance(Class.java:1208)

解决方案

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.

Solution

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)
}

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆