To initialize my logger apparently I need:

val LOGGER : Logger = LoggerFactory.getLogger(Foo::class.java);

如果我这么做了:

val LOGGER : Logger = LoggerFactory.getLogger(Foo::javaClass);

It complains that the parameter type is not compatible with getLogger. However according to the API, both are Class<Foo>. How are they different?

推荐答案

javaClass是一个扩展属性,返回实例化objectruntime Java class.在您的例子中,它被用作属性引用,这将为您提供一个KProperty1<Foo, Class<Foo>>,表示扩展函数本身:

val T.javaClass: java.lang.Class<T>

You could use this in combination with a receiver, e.g. if Foo provided a default constructor you could say:

Foo::javaClass.get(Foo())

可简化为:

Foo().javaClass

Using ::class.java on the other hand, gives you the Java Class<?> as described in "class references" directly. All three possibilities in a simple example:

val kProperty1: KProperty1<Foo, Class<Foo>> = Foo::javaClass
kProperty1.get(Foo()) //class de.swirtz.kotlin.misc.Foo
Foo::class.java //class de.swirtz.kotlin.misc.Foo
Foo().javaClass //class de.swirtz.kotlin.misc.Foo

Kotlin相关问答推荐

如何使用具有名称冲突的限定这个?

如果启用了Flyway迁移,则不能具有配置属性';datources.default.架构-生成

用Quarkus和Reactor重写异步过滤器中的数据流

限制通用Kotlin枚举为特定类型

找不到有效的 Docker 环境

将 java Optional 转换为 Kotlin Arrow Option

按钮无法在 Android Studio 上打开新活动

返回 kotlin 中的标签和 lambda 表达式

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

在 Compose 中使用 Text() 时如何获取文本的大小?

我可以在 Kotlin 中使用接口类型作为构造函数参数吗

使用 Discord4j 交叉发布 Discord 消息

Kotlin 中列表或数组的乘积

.indices 在 kotlin 中的含义是什么?

如何使 TextInputEditText 只读?

如何将 kotlin 集合作为 varagrs 传递?

应用程序在使用 Google Play 服务时遇到问题

如果作为 RxJava Observable 提供,Kotlin 密封类子类需要强制转换为基类

Kotlin类型安全类型别名

在多平台子元素中使用kapt