kotlin掉用java代码 ---> @JvmField 和@JvmName的使用理解

kotlin掉用java代码 ---> @JvmField 和@JvmName的使用理解

假如在java中有以下代码:

public abstract class Base {
    public abstract Integer getId();
}

下面使用kotlin来进行继承该抽象类,那么编辑器就会报以下错误,

Platform declaration ***: The following declarations have the same JVM signature (getId()Ljava/lang/Integer;):

  • public final fun (): Int? defined in com.codelabs.state.todo.Child
  • public open fun getId(): Int defined in com.codelabs.state.todo.Child
class Child() : Base() {
    var id: Int? = null
}

因为kotlin的语法中在调用java中的get和set方法时,是可以进行简写的,也就是,所以上面的报错其实就是在这里会产生冲突。

val id = child.id // 在java class中 其实调用的是 child.getId()
val id2 = child.getId() // 当然也可以这样,就是编辑器会建议你使用第一种方式
解决方法:
  1. @JvmField

    class Child : Base() {
    
        // JvmField 在java class文件中并不为该属性生成get和set方法,直接暴露给外部调用,
        // 也就是使用public修饰
        @JvmField
        var id: Int? = null
    
        override fun getId(): Int {
            return 4
        }
    }
    

    查看该kotlin文件生成的class文件,如下

    public final class Child extends Base {
       @JvmField
       @Nullable
       public Integer id; // 不是private 该属性直接暴露给外部
    
       public int getId() {
          return 4;
       }
    
       public Integer getId() {
          return this.getId();
       }
    }
    
  2. @JvmName

    class Child : Base() {
        // 指定kotlin中的属性在java class文件中的存在的方式,
        // 当child.id 在class文件中其实是调用的是child._getId()
        @get:JvmName("_getId")
        var id: Int? = null
    
        override fun getId(): Int {
            return 4
        }
    }
    

    相应的class文件如下:

    public final class Child extends Base {
       @Nullable
       private Integer id; // private
    
       @JvmName(
          name = "_getId"
       )
       @Nullable
       public final Integer _getId() { // 指定在class文件中的方法名
          return this.id;
       }
    
       public final void setId(@Nullable Integer var1) {
          this.id = var1;
       }
        
       // 下面是kotlin重写方法在class文件中的存在方式,上面是@JvmName的作用
       public int getId() {
          return 4;
       }
    
       public Integer getId() {
          return this.getId();
       }
    }
    
posted @ 2021-09-29 12:07  SowHappy  阅读(530)  评论(0)    收藏  举报