Kotlin直接访问Java字段,而不是使用getter/setter
例如,下面是一个Java类Kotlin直接访问Java字段,而不是使用getter/setter,java,kotlin,Java,Kotlin,例如,下面是一个Java类 public class Thing { ... public int thing; public int getThing() { return thing; } public void setThing(int t) { thing = t; } } 在Kotlin中,如果我想访问东西,我将执行以下操作: val t = Thing() t.thing // get t.thing = 42 //set 在反编译的Kotlin字
public class Thing {
...
public int thing;
public int getThing() { return thing; }
public void setThing(int t) { thing = t; }
}
在Kotlin中,如果我想访问东西
,我将执行以下操作:
val t = Thing()
t.thing // get
t.thing = 42 //set
在反编译的Kotlin字节码中,我看到的是Kotlin使用getter和setter:
t.getThing()
t.setThing(42)
我想知道是否有一种方法可以直接访问字段
t.thing
而不是使用getter和setter?您可以直接从Kotlin代码访问Java字段。因此,如果没有getter,您仍然可以访问t.thing
但我认为当你有一个能手的时候,你不可能进入这个领域。如果您无法编辑Java代码,但仍然希望直接访问该字段(以避免getter或其他方面的副作用),那么可以使用另一个Java类来完成。通过这种方式,您可以管理对字段的访问
public class AnotherThing {
...
public Thing thing;
public getField() { return thing.thing; }
}
我不确定你看到的字节码是否能给你完整的解释 我修改了您的测试类,为基础字段提供了不同的行为:
公共类的东西{
公共物品;
public int getThing(){return thing+1;}
公共无效设置(int t){thing=0;}
}
然后在运行此Kotlin代码时:
fun main(){
val t=事物()
t、 事物=1
println(t.thing)
println(t.getThing())
t、 设置(1)
println(t.thing)
println(t.getThing())
}
我得到:
1
2.
0
1.
这表明
t.thing
实际上是直接获取和设置字段。当您不需要直接访问时,考虑只使用getter和setter(大多数情况下从不):事实证明Intellij的Kotlin字节码有点误导,在实际的.class文件中,它确实是直接字段访问。