Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

255
Views
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?

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

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.

over 4 years ago · Santiago Trujillo Report

0

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.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!