为什么在注释处理器中评估伴侣对象修饰符时总是私有的?

时间:2018-09-19 09:26:07

标签: android kotlin annotations annotation-processing

我有一个自定义注释,其RetentionAnnotationRetention.SOURCE,并且我想确保被注释的变量是public static,但是我对kotlin随播对象有问题,它们似乎即使我明确声明了它们private,也仍然是public

这是我的注释代码:

class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
}

companion object {
    @AZNEncryptor("the raw string")
    public var str: String? = null
}
}

我的注释处理器代码是:

    override fun process(set: Set<TypeElement>, roundEnvironment: RoundEnvironment): Boolean {        roundEnvironment.getElementsAnnotatedWith(AZNEncryptor::class.java).forEach { element ->

        if (element.getKind() != ElementKind.FIELD) {
            processingEnv.messager.printMessage(Diagnostic.Kind.ERROR, "this annotation can only be applied to the variables.")
            return true
        }


        val variableElement = element as VariableElement

        for(modifier in variableElement.modifiers)
        {
            processingEnv.messager.printMessage(Diagnostic.Kind.WARNING,  modifier.name)
        }

        if (!variableElement.modifiers.contains(Modifier.STATIC) || !variableElement.modifiers.contains(Modifier.PUBLIC)) {
            processingEnv.messager.printMessage(Diagnostic.Kind.ERROR, "the annotated variable must be a \"public static\"")
            return true
        }

        generateClass("constants", variableElement.simpleName.toString())

    return true
}

1 个答案:

答案 0 :(得分:0)

我发现了问题。当我反编译Kotlin代码字节码时,我得到了以下Java代码:

public final class MainActivity extends AppCompatActivity {
  @Nullable
  private static String str;

  .
  .
  .
 public static final class Companion {
  @Nullable
  public String getStr() {
     return MainActivity.str;
  }

  public void setStr(@Nullable String var1) {
     MainActivity.str = var1;
  }

  private Companion() {
  }

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

如您所见,变量变为private static。我只需要使用@JvmField来解决此问题,现在反编译的字节码如下所示:

public final class MainActivity extends AppCompatActivity {
  @JvmField
  @Nullable
  public static String str;

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

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