我有一个接受Class个参数的Java方法.我需要将Integer.class传递给它,但是来自Kotlin代码.我try 了Int::class.java,但是这不起作用,因为int.class被传递给函数.我的问题是,如何从Kotlin访问Integer.class.

Java

void foo(Class clazz);

Kotlin

foo(Int::class.java) // does not work, int.class gets passed to foo

推荐答案

You must use the KClass#javaObjectType to get the wrapper type class in Kotlin:

返回对应于给定KClass实例的Java Class实例.对于primitive个类型,它返回相应的wrapper个类.

For example:

//                  v--- java.lang.Integer
println(Int::class.javaObjectType)

//                  v--- int
println(Int::class.java)

Kotlin相关问答推荐

如何在Kotlin中为两个数据类创建可重用的方法?

只能在元素区域中点击的Jetpack Compose列

在Kotlin项目中使用Free Fair AspectJ插件(使用Gradle)

两个LocalDateTime之间的Kotlin差异

Kotlin SIZE_BYTES

Rabin-Karp字符串匹配的实现(Rolling hash)

如何使用函数类型或 lambdas 作为 Kotlin 上下文接收器的类型?

为什么这个 Kotlin 代码不起作用? (如果 str[index] 在列表中,则打印)

即使 Kotlin 的 `Map` 不是 `Iterable`,它如何以及为什么是可迭代的?

使用纯 Kotlin 函数作为 Junit5 方法源

Kotlin 使用迭代索引过滤 lambda 数组

具有多个不同类型来源的 LiveData

在 Kotlin 中,当枚举类实现接口时,如何解决继承的声明冲突?

Kotlin 1.2.21 + SimpleXml 2.3.0 - consume List error (must mark set get method)

Kotlin 中 lambda 表达式中的默认参数

无法创建类 ViewModel kotlin 的实例

TypeConverter()在Android的TypeConverter错误中具有私有访问权限

如何启用spring security kotlin DSL?

Kotlin - 如何获取注释属性值

任务':app:kaptDebugKotlin'的Kotlin执行失败