'I want to detect if a JVM Class is a Kotlin class or not
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?"
Solution 1:[1]
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()
The class kotlin.Metadata
is not accessed directly because it is marked internal
in the Kotlin runtime.
Solution 2:[2]
While the other answer may work (possibly outdated), many reflection features will not work on file classes or generated classes (lambdas, etc).
However, there is a parameter in the @Metadata annotation that can tell you if the class is what you are looking for:
A kind of the metadata this annotation encodes. Kotlin compiler recognizes the following kinds (see KotlinClassHeader.Kind):
1 Class
2 File
3 Synthetic class
4 Multi-file class facade
5 Multi-file class partThe class file with a kind not listed here is treated as a non-Kotlin file.
@get:JvmName("k")
val kind: Int = 1
We can take advantage of this to make sure we are only getting real classes:
val Class<*>.isKotlinClass get() = getAnnotation(Metadata::class.java)?.kind == 1
I can confirm this works in 1.6.20
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | bush |