英文:
Kotlin access Java field directly instead of using getter/setter
问题
例如,这是一个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 // 获取
t.thing = 42 // 设置
在反编译的Kotlin字节码中,我看到Kotlin在使用getter和setter:
t.getThing()
t.setThing(42)
我想知道是否有一种方法可以直接访问字段 t.thing
,而不是使用getter和setter?
英文:
For example, here is a Java class
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:
val t = Thing()
t.thing // get
t.thing = 42 //set
In the decompiled Kotlin bytecode, what I see is Kotlin using getter and 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?
答案1
得分: 2
我不确定您正在查看的字节码是否为您提供了完整的解释。
我修改了您的测试类,为 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
实际上是直接获取并设置了该字段。
英文:
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:
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:
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.
答案2
得分: 0
你可以直接从 Kotlin 代码访问 Java 字段。所以,如果没有 getter,你仍然可以访问 t.thing
。
但是我认为当你有一个 getter 时,无法直接访问字段。如果你无法编辑 Java 代码,但仍希望直接访问字段(以避免 getter 中的副作用之类的),你可以使用另一个 Java 类来实现。这样你就可以管理对该字段的访问。
public class AnotherThing {
...
public Thing thing;
public getField() { return thing.thing; }
}
英文:
You can access Java fields directly from the Kotlin code. So, if you don't have a getter, you can still access t.thing
.
But I don't think it's possible to access the field when you have a 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. This way you can manage access to the field.
public class AnotherThing {
...
public Thing thing;
public getField() { return thing.thing; }
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论