静态字段

Kotlin中在命名对象或伴生对象中声明的属性:

  1. class Department {
  2. ...
  3. companion object {
  4. var innerID = "X001"
  5. @JvmField
  6. var innerName = "DEP"
  7. }
  8. }

innerID、innerName这两个字段的区别在于可见性上:

  1. @NotNull
  2. private static String innerID = "X001";
  3. @JvmField
  4. @NotNull
  5. public static String innerName = "DEP";

这个私有的innerID通过Companion对象来封装,提供出public的getInnerID() 、setInnerID来访问:

  1. public static final class Companion {
  2. @NotNull
  3. public final String getInnerID() {
  4. return Department.innerID;
  5. }
  6. public final void setInnerID(@NotNull String var1) {
  7. Intrinsics.checkParameterIsNotNull(var1, "<set-?>");
  8. Department.innerID = var1;
  9. }
  10. private Companion() {
  11. }
  12. // $FF: synthetic method
  13. public Companion(DefaultConstructorMarker $constructor_marker) {
  14. this();
  15. }
  16. }

我们在Java访问的innerID时候,是通过Companion来访问:

  1. Department.Companion.getInnerID()

而我们使用@JvmField注解的字段innerName ,Kotlin编译器会把它的访问权限设置是public的,这样我们就可以这样访问这个属性字段了:

  1. Department.innerName