我想检测JVM类是否是Kotlin类 [英] I want to detect if a JVM Class is a Kotlin class or not

查看:80
本文介绍了我想检测JVM类是否是Kotlin类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

与通用Java类相比,如果我遇到Kotlin类,我想做一些特殊的功能.如何确定这是否是Kotlin班?

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?

我希望如果类不是Kotlin,调用someClass.kotlin会引发异常或失败.但是它包装了Java类就好了.然后我注意到,如果我执行someClass.kotlin.primaryConstructor,那么即使所有Java类都具有默认构造函数,对于所有Java类来说似乎也都是null,这是一个很好的标记吗?但是那还能为Kotlin类返回null吗?

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为其所有类添加了注释,您可以通过名称安全地检查其存在.这是一个实现细节,并且可能会随时间而变化,但是某些关键库使用此注释,因此可能会无限期地保持正常状态.

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"
    }
}

可以用作:

someClass.isKotlinClass()

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

The class kotlin.Metadata is not accessed directly because it is marked internal in the Kotlin runtime.

这篇关于我想检测JVM类是否是Kotlin类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆