Ted
Ted

Reputation: 1611

kotlin: check if a class is object class?

I have a kotlin object and a java class like:

KotlinObject.kt

object KotlinObject{
....
}

JavaClass.java

class JavaClass {
...
}

and a kotlin function to check:

fun foo(cls: Class<*>): Any {
   if (cls is kotlin's object) { //how to do this?
      return ?  //wanna return object's instance
   } else {
      return cls.newInstance()
   }    
}

I can pass kotlin object or java class to this function:

foo(KotlinObject::class.java)
foo(JavaClass::class.java)

so is it possible to tell which one is kotlin's object?

Upvotes: 3

Views: 4755

Answers (2)

Alexander Egger
Alexander Egger

Reputation: 5302

Thanks to @Alexey Romanov for pointing out in the comments that the Kotlin class information is available from Class<*>.

fun foo(cls: Class<*>) {
    if (cls.kotlin.objectInstance != null)
        println("KotlinObject")
    else
        println("Other class")
}

My original approach was to mimic Kotlins KClass.objectInstance.

I keep this for reference but please use the solution above.

fun foo(cls: Class<*>) {
    val objectInstance = cls.declaredFields.firstOrNull {
        it.type == cls && it.name == "INSTANCE"
    }

    if (objectInstance != null)
        println("KotlinObject")
    else
        println("Other class")
}

Be aware that any Java Singleton using the name 'INSTANCE' for the singleton field will also be reported as Kotlin object in that case.

Upvotes: 6

CryptoFool
CryptoFool

Reputation: 23079

Got it!

object KotlinObject{}
class JavaClass {}

fun foo(cls: KClass<*>) {
    if (cls.objectInstance != null)
        println("It's a Kotlin object")
    else
        println("It's NOT a Kotlin object")
}

fun main(args: Array<String>) {
    foo(KotlinObject::class)
    foo(JavaClass::class)
}

Output:

It's a Kotlin object
It's NOT a Kotlin object

If, for some reason, you must pass the Java class, then I couldn't figure out any way to do this. I think all the distinction is then gone.

NOTE: This works even if JavaClass is defined in a Java file. Every object in Kotlin is of a KClass type regardless of how and where it was defined. That is, ::class works on any object in Kotlin.

Upvotes: 2

Related Questions