【问题标题】:in kotlin, how to access protected static member in parent class from sub class在 kotlin 中,如何从子类访问父类中受保护的静态成员
【发布时间】:2022-01-17 01:41:55
【问题描述】:

它是在 java 中工作的代码,但转换为 kotlin 后它无法编译。

有一个基类,它有一些定义为伴生对象中的静态受保护成员:

abstract class ParentClass {

   companion object {
        @JvmField
        final protected val SERVICE_TYPE_A = "the_service_type_a"    
   }
}

和子类:

class ChildClass: ParentClass {
    public override fun getServiceType(): String {
        return SERVICE_TYPE_A. //<== got compile error
    }
}

它无法编译。

如何从子类访问父类的静态受保护成员?

【问题讨论】:

    标签: kotlin static protected


    【解决方案1】:

    您需要改用@JvmStatic,如下所示:

    abstract class ParentClass {
        companion object {
            @JvmStatic
            protected val SERVICE_TYPE_A = "the_service_type_a"
        }
    
        abstract fun getServiceType(): String
    }
    

    SERVICE_TYPE_A 中的 final 关键字是多余的,因为在 Kotlin 中默认情况下所有内容都是 final。这也意味着如果你想扩展ParentClass,那么你需要将它显式定义为open

    那么您的ChildClass 将如下所示:

    class ChildClass: ParentClass() {
        override fun getServiceType(): String {
            return SERVICE_TYPE_A
        }
    }
    

    【讨论】:

    • 这似乎不起作用。 ParentClass 是简化示例(错过了 open 关键字),它实际上是一个抽象类,我更新了问题。
    • 请避免过度简化问题,否则您会得到错误的答案。我已经根据更新的问题更新了我的答案。请检查它;)
    • 感谢您的帮助。使用@JvmStatic 使其可编译,但也会在java 代码中生成protected final String getSERVICE_TYPE_A(),并在SERVICE_TYPE_A 被引用的地方得到错误IllegalAccessError: tried to access method com.xxx.ParentClass$Companion.getSERVICE_TYPE_A()。它可能需要一些重构才能使其工作(尤其是从 java 代码调用)。
    • 但是你没有提到这应该在Java代码中使用。您提到您正在将 Java 转换为 Kotlin。我假设你所有的代码都是 Kotlin。
    猜你喜欢
    • 2016-07-05
    • 1970-01-01
    • 1970-01-01
    • 2013-10-16
    • 2012-12-01
    • 2013-11-30
    • 2015-06-30
    • 2018-02-09
    • 2018-09-15
    相关资源
    最近更新 更多