簡體   English   中英

Kotlin 直接訪問 Java 字段而不是使用 getter/setter

[英]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 // get
t.thing = 42 //set

在反編譯的 Kotlin 字節碼中,我看到的是 Kotlin 使用 getter 和 setter:

t.getThing()
t.setThing(42)

我想知道是否有一種方法可以直接訪問字段t.thing而不是使用 getter 和 setter?

我不確定您正在查看的字節碼是否為您提供了完整的解釋。

我修改了您的測試類,為基礎字段提供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實際上是直接獲取和設置字段。

您可以直接從 Kotlin 代碼訪問 Java 字段。 所以,如果你沒有 getter,你仍然可以訪問t.thing

但是我認為當你有一個 getter 時就不可能訪問這個領域。 如果您無法編輯 Java 代碼但仍想直接訪問該字段(以避免 getter 或其他東西中的副作用),您可以使用另一個 Java 類來完成。 這樣您就可以管理對該字段的訪問。

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