在Kotlin中扩展`org.jooq.Converter<Any?, Long?>`。

huangapple go评论80阅读模式
英文:

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&lt;Any?, Long?&gt; in Kotlin. It requires me to override several functions one of which is

override fun fromType(): Class&lt;Any?&gt; = ...

The question is: In Kotlin how do I get the type of Any?? The following does not work:

override fun fromType(): Class&lt;Any?&gt; = 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&lt;Any&gt;, 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&lt;Any?&gt;

huangapple
  • 本文由 发表于 2023年7月7日 05:21:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/76632589.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定