Kotlin 注解之JvmStatic

10/19 11:26
阅读数 20
class TestJvmStatic {

    companion object {
        const val a = 1
        val b = 2
        var c = 3

        @JvmField
        var d = 4

        @JvmField
        val e = 5

        @JvmStatic
        fun doOperateA() {

        }

        fun doOperateB() {}

    }
}

转换成Java代码如下:

public final class TestJvmStatic {
   public static final int a = 1;
   private static final int b = 2;
   private static int c = 3;
   @JvmField
   public static int d = 4;
   @JvmField
   public static final int e = 5;
   public static final TestJvmStatic.Companion Companion = new TestJvmStatic.Companion((DefaultConstructorMarker)null);

   @JvmStatic
   public static final void doOperateA() {
      Companion.doOperateA();
   }

   
   public static final class Companion {
      public final int getB() {
         return TestJvmStatic.b;
      }

      public final int getC() {
         return TestJvmStatic.c;
      }

      public final void setC(int var1) {
         TestJvmStatic.c = var1;
      }

      @JvmStatic
      public final void doOperateA() {
      }

      public final void doOperateB() {
      }

      private Companion() {
      }

      // $FF: synthetic method
      public Companion(DefaultConstructorMarker $constructor_marker) {
         this();
      }
   }
}

 

在Java文件中调用:

TestJvmStatic.doOperateA();
TestJvmStatic.Companion.doOperateB();
int a = TestJvmStatic.a;
int e = TestJvmStatic.e;
int d = TestJvmStatic.d;
TestJvmStatic.Companion.getB();
TestJvmStatic.Companion.getC();

通过对比可以发现:@JvmStatic 和 @JvmField 注解,才能使方法或者字段暴露为静态方法或静态字段,这样Java调用方式和正常的Java静态方法的调用方式一样了。

展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部