本文是既 JvmName 註解在 Kotlin 中的應用 和JvmMultifile 註解在 Kotlin 中的應用 的第三篇關於 Kotlin的註解文章。
介紹的內容比較簡單,主要是包含了JvmField和JvmStatic兩個。
@JvmField
示例代碼聲明
1
2
3
package com.example.jvmannotationsample
class Developer ( @JvmField val name : String , val ide : String )
使用@JvmField,我們在Java中調用的時候,可以直接使用屬性名,而不是對應的getter方法。
調用代碼對比
1
2
3
4
//test jvmField
Developer developer = new Developer ( "Andy" , "Android Studio" );
System . out . println ( developer . getIde ()); // not using JvmField
System . out . println ( developer . name ); // using JvmField
@JvmStatic
除此之外,對於靜態屬性和靜態方法的實現,我們也可以使用@JvmStatic實現,
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package com.example.jvmannotationsample
class Sample {
companion object {
@JvmStatic
val TAG_NAME = "Sample"
val NON_STATIC_VALUE = "non_static_value"
@JvmStatic fun callStatic () {
}
fun callNonStatic () {
}
}
}
調用代碼如下
1
2
3
4
5
6
//JVM static method
Sample . callStatic ();
Sample . Companion . callNonStatic ();
Sample . getTAG_NAME ();
Sample . Companion . getNON_STATIC_VALUE ();
Companion
Kotlin中我們可以藉助object
實現靜態的形式,比如下面的代碼
1
2
3
4
5
6
7
8
9
package com.example.jvmannotationsample
class SomeClass {
companion object {
fun getCommonProperties (): List < String > {
return emptyList ()
}
}
}
其實除此之外,我們還能命名companion的名稱,如下代碼
1
2
3
4
5
6
7
8
9
package com.example.jvmannotationsample
class AnotherClass {
companion object Assistant {
fun scheduleSomething () {
}
}
}
調用代碼示例
1
2
3
//test companion
SomeClass . Companion . getCommonProperties ();
AnotherClass . Assistant . scheduleSomething ();
相關文章推薦