Kotlin companion objects and reflection

2.6k Views Asked by At

Ran into something interesting when using companion objects and Java reflection. I'm not sure if its intended or not, or if I'm just not understanding things fully.

I have this code

public class TestClass {
  companion object {
        public platformStatic var data: String? = null
  }
}

The data field eventually gets filled via reflection from another class.

What I've found is that if I access the class with TestClass.javaClass, I get the internal companion class which only has methods for accessing that field. Accessing it via javaClass<TestClass>() gets me the expected Java class with full access to the fields.

Am I just missing something obvious? Is there a reason for this behavior?

1

There are 1 best solutions below

1
On

Static fields are stored in the outer class to facilitate Java interop: you can say TestClass.data in Java to refer to that field (this should be why you marked it platformStatic in the first place).