I want to do special functionality if I encounter a Kotlin class as compared to a generic Java class. How can I detect if it is a Kotlin class?

I was hoping that calling someClass.kotlin would throw an exception or fail if the class wasn't Kotlin. But it wraps Java classes just fine. Then I noticed that if I do someClass.kotlin.primaryConstructor it seems to be null for all java classes even if they have a default constructor, is that a good marker? But can that return null for a Kotlin class as well?

What is the best way to say "is this a Kotlin class?"

推荐答案

Kotlin adds an annotation to all of its classes, and you can safely check for its existence by name. This is an implementation detail and could change over time, but some key libraries use this annotation so it is likely to be ok indefinitely.

fun Class<*>.isKotlinClass(): Boolean {
    return this.declaredAnnotations.any {
        it.annotationClass.qualifiedName == "kotlin.Metadata"
    }
}

Can be used as:

someClass.isKotlinClass()

kotlin.Metadata不能直接访问,因为它在Kotlin运行时被标记为internal.

Kotlin相关问答推荐

了解Kotlin函数

调用即发即忘方法--哪个作用域?

Kotlin -从列表中获取特定过滤器的唯一列表值

Jetpack Compose Material3和Material2 Slider onValueChangeFinded()的行为不同

如何在Android应用判断上运行多个查询

在构造函数中创建内部类实例时,只能使用包含类的接收器调用内部类的构造函数

如何在数据类中删除空格 (String)?

为什么 Kotlin 在将协变类型参数转换为不变类型参数时会产生 Unchecked Cast 警告?

如何使用 Firebase 和 Kotlin 在文本 (Jetpack Compose) 中显示当前用户名?

在 Kotlin 中,为什么在 `+` 之前但在 `.` 之前没有换行符?

如何在 Kotlin 中使用具有继承的泛型

如何在 Android 的 Fragment 中使用 setUserVisibleHint

下拉通知面板时是否可以暂停Android中的任何视频(媒体播放器)应用程序?

Kotlin 有 array.indexOf 但我无法弄清楚如何做 array.indexOfBy { lambda }

将 Android Studio 升级到 3.1.0 后的 Android Support 插件错误

从 Spring WebFlux 返回 Flux 返回一个字符串而不是 JSON 中的字符串数组

Kotlin中的下划线名称是为什么保留的?

在kotlin中,如何模拟封装回调函数?

以Kotlin为单位的货币数据类型

如何在 Fragment 中使用 Anko DSL?