Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 541
Jayson Minard Avatar asked Oct 01 '16 12:10

Jayson Minard


People also ask

Can Kotlin class be used in Java?

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.

What is Kotlin class Java?

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.


1 Answers

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.

like image 66
2 revs Avatar answered Sep 27 '22 21:09

2 revs