Kotlin 的 @JvmStatic 和 @JvmField 注解


這是關於 Java 靜態方法和靜態變量的一段代碼:

public class TestStatic {
    private int otherField = 0;

    public static final BigInteger BIG_INTEGER = BigInteger.ONE;

    public static void method() {
        System.out.println("call method");
    }
}

我們把它轉換成 Kotlin 代碼,會得到這樣的結果:

class TestStatic {
    private val otherField = 0

    companion object {
        val BIG_INTEGER = BigInteger.ONE

        fun method() {
            println("call method")
        }
    }
}

靜態方法和靜態變量會被放在 companion object 當中,成為伴生方法和伴生常量。而這時候,會發現在 Java 中調用它們的方式會不一樣,如下:

public static void main(String[] args) {
    TestStatic.Companion.method();
    BigInteger bigInteger = TestStatic.Companion.getBIG_INTEGER();
}

如果要使轉換后的 Kotlin 代碼在 Java 上調用起來和以前的習慣一樣,則需要分別使用 @JvmStatic 和 @JvmField 注解,才能使它們暴露為靜態方法或靜態字段,如下:

object TestStatic {
    @JvmField 
val BIG_INTEGER
= BigInteger.ONE @JvmStatic fun method() { println("call method") } }

 

這樣 Java 對 Kotlin 的調用習慣就和以前一樣了:

public static void main(String[] args) {
    TestStatic.method();
    BigInteger bigInteger = TestStatic.BIG_INTEGER;
}

關於這一點,在《Android Kotlin 指南》的文檔中有提到,分別如下:

伴生函數:

在 “companion object” 中的公共函數必須用使用 @JvmStatic 注解才能暴露為靜態方法。

如果沒有這個注解,這些函數僅可用作靜態 Companion 字段上的實例方法。

伴生常量:

在 companion object 中的公共、非 const 的屬性 實際上為常量 必須用 @JvmField 注解才能暴露為靜態字段。

如果沒有這個注解,這些屬性只能作為靜態 Companion 字段中奇怪命名的 ‘getters’ 實例。而只使用 @JvmStatic 而不是 @JvmField 的話,會將奇怪命名的 ‘getters’ 移到類的靜態方法中,但仍然是不正確的。

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM