androidkotlinkotlin-reflectkotlin-companion

Kotlin static constant field returning modified String value


I'm trying to reach a constant String value of the Class name. But I really don't understand why I get a modified String value. Here is the code that I'm working on:

class TestClass {
    companion object {
            @JvmField
            val TAG1: String = this::class.java.name as String
            val TAG2: String = this::javaClass.name 
    } 
}

In another class trying to reach the value like this:

class ComboClass {
    override fun onStart() {
       val tag1 = TestClass.TAG1
       val tag2 = TestClass.TAG2

       // tag1 "packagePath.TestClass$Companion"
       // tag2 "packagePath.TestClass$Companion"
    }
}

Why Am I getting packagePath.TestClass$Companion at the end of the String value? I'm expecting to get packagePath.TestClass

Thanks


Solution

  • Why Am I getting packagePath.TestClass$Companion at the end of the String value?

    Companion objects have classes of their own, in this case the object is of type TestClass$Companion, so this::class.java.name as String and this::javaClass.name both give you the name of the companion object's class.

    How to get TestClass

    You will want to use TestClass::class.java.name and TestClass::javaClass.name instead to get TestClass