简体   繁体   English

无法访问 Java 子类中父 Kotlin 类的受保护成员变量

[英]Not able to access protected member variable of Parent Kotlin class in Java child class

abstract class Parent {

    protected var name : String

}

class Child extends Parent {

    private void childMethod() {
         name = "child";
    }
}

in Child class it gives me error name has private access in xxxChild (xxx is package name)在 Child 类中,它给了我错误名称在 xxxChild 中具有私有访问权限(xxx 是包名称)

In java child class we can access the protected member variable of parent as getName().在java子类中,我们可以通过getName()访问parent的protected成员变量。 Like a getter method is auto-generated.就像 getter 方法是自动生成的。 I am new to Kotlin, need to dig out more how the method is auto-generated.我是 Kotlin 的新手,需要深入了解该方法是如何自动生成的。

If you want to access it as a field from Java, you should annotate the Kotlin property with @JvmField .如果您想从 Java 中将其作为字段访问,您应该使用@JvmField注释 Kotlin 属性。 Note that per that link, you can only annotate a property with @JvmField if it has a backing field, is not private, does not have open , override or const modifiers, and is not a delegated property (none of which apply here, so you're fine).请注意,根据该链接,您只能使用@JvmField注释一个属性,如果它有一个支持字段,不是私有的,没有openoverrideconst修饰符,并且不是委托属性(这些都不适用这里,所以你没事)。

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

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