Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

254
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda