Get companion class in companion object

Viewed 5588

Is there a way to get the javaClass of the companion class inside a companion object without knowing it's name?

I suppose I could get it by doing something like this:

open class TestClass {
    companion object {
        init {
            val clazz = Class.forName(this::class.java.canonicalName.removeSuffix(".Companion"))
        }
    }    
}

However, this does not work for class InheritingClass : TestClass(). It would still give me TestClass, not InheritingClass.

I was hoping for something more straightforward like this::class.companionClass.

3 Answers

Getting the class of the companion object of a given class will look like this:

TestClass::class.companionObject

Here's an example:

class TestClass {

    companion object {
        fun sayHello() = "Hello world"
    }
}

If you want to get the class that contains the companion, since the latter is always an inner class of the former,

class TestClass {

    companion object {
        fun whichIsMyParentClass() = this::class.java.declaringClass // It'll return TestClass
    }
}

And to further simplify, you'll also want to create an extension property:

import kotlin.reflect.KClass

val <T : Any> KClass<T>.companionClass get() =
    if (isCompanion)
        this.java.declaringClass
    else
        null

So, whenever you want to get the parent class of the companion object,

class TestClass {

    companion object {
        fun whichIsMyParentClass() = this::class.companionClass // It'll return TestClass
    }
}

If you need to print the class name, you can add simpleName, such as

this::class.java.declaringClass.simpleName
Related