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?"
Android developers are generally aware that Java can interact with Kotlin relatively seamlessly. Kotlin has been designed from the beginning to fully interoperate with Java, and both JetBrains and Google have pushed in that direction.
By using ::class , you get an instance of KClass. It is Kotlin Reflection API, that can handle Kotlin features like properties, data classes, etc. By using ::class. java , you get an instance of Class. It is Java Reflection API, that interops with any Java reflection code, but can't work with some Kotlin features.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With