13

Kotlin 注解 第三篇 @JvmField 与 @JvmStatic - 技术小黑屋

 4 years ago
source link: https://droidyue.com/blog/2019/12/22/kotlin-annotation-jvmfiled-and-jvmstatic-and-object/?
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

本文是既 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();

相关文章推荐


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK