kotlin @JvmStatic 和 @JvmField

两个注解都是与java互操作相关。

原代码:

class AnnotationTest{
    companion object {
        var name:String = ""
    }
}

对应的java代码:

public final class AnnotationTest {
   @NotNull
   private static String name = "";
   public static final AnnotationTest.Companion Companion = new AnnotationTest.Companion((DefaultConstructorMarker)null);

   public static final class Companion {
      @NotNull
      public final String getName() {
         return AnnotationTest.name;
      }

      public final void setName(@NotNull String var1) {
         Intrinsics.checkParameterIsNotNull(var1, "");
         AnnotationTest.name = var1;
      }

      private Companion() {
      }

      public Companion(DefaultConstructorMarker $constructor_marker) {
         this();
      }
   }
}

可以看到name属性属于AnnotationTest类,并且AnnotationTest的伴生对象生成了对应的get、set方法。

一.@JvmStatic

可以修饰属性或者方法。
修饰属性时:

class AnnotationTest{
   companion object {
       @JvmStatic
       var name:String = ""
   }
}

对应的java代码:

public final class AnnotationTest {
   @NotNull
   private static String name = "";
   public static final AnnotationTest.Companion Companion = new AnnotationTest.Companion((DefaultConstructorMarker)null);

   @NotNull
   public static final String getName() {
      AnnotationTest.Companion var10000 = Companion;
      return name;
   }

   public static final void setName(@NotNull String var0) {
      AnnotationTest.Companion var10000 = Companion;
      name = var0;
   }

   public static final class Companion {
      @JvmStatic
      public static void name$annotations() {
      }

      @NotNull
      public final String getName() {
         return AnnotationTest.name;
      }

      public final void setName(@NotNull String var1) {
         Intrinsics.checkParameterIsNotNull(var1, "");
         AnnotationTest.name = var1;
      }

      private Companion() {
      }

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

可以看到在AnnotationTest中为name属性生成了get和set方法,同时伴生对象也保留着get和set方法。

二.@JvmField

只能修饰属性

当使用@JvmField修饰时

class AnnotationTest{
    companion object {
        @JvmField
        var name:String = ""
    }
}

对应的java代码:

import kotlin.Metadata;
import kotlin.jvm.JvmField;
import kotlin.jvm.internal.DefaultConstructorMarker;
import org.jetbrains.annotations.NotNull;

public final class AnnotationTest {
   @JvmField
   @NotNull
   public static String name = "";
   public static final AnnotationTest.Companion Companion = new AnnotationTest.Companion((DefaultConstructorMarker)null);

   public static final class Companion {
      private Companion() {
      }

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

可以看到伴生对象的get和set方法消失了,同时AnnotationTest中的name可见性为public。

你可能感兴趣的:(kotlin @JvmStatic 和 @JvmField)