简体   繁体   English

Kotlin伴侣对象和反射

[英]Kotlin companion objects and reflection

Ran into something interesting when using companion objects and Java reflection. 使用伴随对象和Java反射时遇到一些有趣的事情。 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. 最终通过另一个类的反射填充data字段。

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. 我发现的是,如果我使用TestClass.javaClass访问该类,则会得到内部的伴随类,该类仅具有用于访问该字段的方法。 Accessing it via javaClass<TestClass>() gets me the expected Java class with full access to the fields. 通过javaClass<TestClass>()进行访问将获得对字段具有完全访问权限的预期Java类。

Am I just missing something obvious? 我只是想念一些明显的东西吗? Is there a reason for this behavior? 有这种现象的原因吗?

静态字段存储在外部类中以方便Java互操作:您可以说Java中的TestClass.data引用该字段(这应该是为什么您首先将其标记为platformStatic原因)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM