英文:
Extension of `org.jooq.Converter<Any?, Long?>` in Kotlin
问题
在Kotlin中,要获取Any?
类型的Class,可以使用以下方式:
override fun fromType(): Class<Any?> = Any::class.java
英文:
I'm writing a converter for JOOQ which extends Converter<Any?, Long?>
in Kotlin. It requires me to override several functions one of which is
override fun fromType(): Class<Any?> = ...
The question is: In Kotlin how do I get the type of Any?
? The following does not work:
override fun fromType(): Class<Any?> = Any?::class.java
答案1
得分: 1
From the JVM's point of view, there is no separate "class" that represents Any?
, as opposed to Any
. Any?
and Any
are all just java.lang.Object
. The JVM does not care about nullability.
So if you are to return "a Class
object representing the class Any?
," you can just return what is known as Object.class
in Java, or Any::class.java
in Kotlin.
The type of Any::class.java
is Class<Any>
, but that doesn't matter because generic types are erased anyway. What matters is that the Class
object representing Any
and the one representing Any?
are the same object. Therefore, it is safe to do an unchecked cast:
override fun fromType() = Any::class.java as Class<Any?>
英文:
From the JVM's point of the view, there is no separate "class" that represents Any?
, as opposed to Any
. Any?
and Any
are all just java.lang.Object
. The JVM does not care about nullability.
So if you are to return "a Class
object representing the class Any?
", you can just return what is known as Object.class
in Java, or Any::class.java
in Kotlin.
The type of Any::class.java
is Class<Any>
, but that doesn't matter because generic types are erased anyway. What matters is that the Class
object representing Any
and the one representing Any?
are the same object. Therefore, it is safe to do an unchecked cast:
override fun fromType() = Any::class.java as Class<Any?>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论