【问题标题】:Kotlin access Java field directly instead of using getter/setterKotlin 直接访问 Java 字段,而不是使用 getter/setter
【发布时间】:2020-10-04 09:12:02
【问题描述】:

例如,这里是一个 Java 类

public class Thing {
    ...
    public int thing;
    public int getThing() { return thing; }
    public void setThing(int t) { thing = t; }
}

在 Kotlin 中,如果我想访问 thing,我会执行以下操作:

val t = Thing()
t.thing // get
t.thing = 42 //set

在反编译的 Kotlin 字节码中,我看到的是 Kotlin 使用 getter 和 setter:

t.getThing()
t.setThing(42)

不知道有没有办法直接访问字段t.thing而不是使用getter和setter?

【问题讨论】:

标签: java kotlin


【解决方案1】:

我不确定您正在查看的字节码是否为您提供了完整的解释。

我修改了您的测试类,为基础字段提供 getThing()setThing() 不同的行为:

public class Thing {
    public int thing;
    public int getThing() { return thing + 1; }
    public void setThing(int t) { thing = 0; }
}

然后在运行这个 Kotlin 代码时:

fun main() {
    val t = Thing()
    t.thing = 1
    println(t.thing)
    println(t.getThing())

    t.setThing(1)
    println(t.thing)
    println(t.getThing())
}

我明白了:

1
2
0
1

这表明t.thing实际上是直接获取和设置字段。

【讨论】:

  • 原来 Intellij 的 Kotlin 字节码有点误导,在实际的 .class 文件中确实是直接字段访问。
【解决方案2】:

您可以直接从 Kotlin 代码访问 Java 字段。所以,如果你没有getter,你仍然可以访问t.thing

但我认为当你有一个 getter 时是不可能访问该字段的。如果您无法编辑 Java 代码但仍想直接访问该字段(以避免 getter 或其他东西的副作用),您可以使用另一个 Java 类来完成。这样您就可以管理对该字段的访问。

public class AnotherThing {
    ...
    public Thing thing;
    public getField() { return thing.thing; }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-02
    • 1970-01-01
    • 2011-09-06
    • 1970-01-01
    • 2013-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多