简体   繁体   English

Kotlin 直接访问 Java 字段而不是使用 getter/setter

[英]Kotlin access Java field directly instead of using getter/setter

For example, here is a Java class例如,这里是一个 Java 类

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

In Kotlin, if I want to access thing , I would do the following:在 Kotlin 中,如果我想访问thing ,我会执行以下操作:

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

In the decompiled Kotlin bytecode, what I see is Kotlin using getter and setter:在反编译的 Kotlin 字节码中,我看到的是 Kotlin 使用 getter 和 setter:

t.getThing()
t.setThing(42)

I wonder if there is a way to directly access the field t.thing instead of using getter and setter?我想知道是否有一种方法可以直接访问字段t.thing而不是使用 getter 和 setter?

I'm not sure the byte code you're looking at is giving you you the full explanation.我不确定您正在查看的字节码是否为您提供了完整的解释。

I modified your test class to give getThing() and setThing() different behaviour to the underlying field:我修改了您的测试类,为基础字段提供getThing()setThing()不同的行为:

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

Then when running this Kotlin code:然后在运行此 Kotlin 代码时:

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

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

I get:我得到:

1
2
0
1

Which indicates that t.thing is in fact getting and setting the field directly.这表明t.thing实际上是直接获取和设置字段。

You can access Java fields directly from the Kotlin code.您可以直接从 Kotlin 代码访问 Java 字段。 So, if you don't have a getter, you can still access t.thing .所以,如果你没有 getter,你仍然可以访问t.thing

But I don't think it's possible to access the field when you have a getter.但是我认为当你有一个 getter 时就不可能访问这个领域。 If you cannot edit the Java code but still want to access the field directly (to avoid side-effects in a getter or something), you can do it using another Java class.如果您无法编辑 Java 代码但仍想直接访问该字段(以避免 getter 或其他东西中的副作用),您可以使用另一个 Java 类来完成。 This way you can manage access to the field.这样您就可以管理对该字段的访问。

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

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

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