0

i have a custom annotation which its Retention is AnnotationRetention.SOURCE and i want to make sure that the annotated variable is a public static but im having problem with kotlin companion objects and they seem to be private even when i explicitly declare them public.

here is my annotated code:

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
}
}

and my annotation processor code is:

    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
}
Raedwald
  • 46,613
  • 43
  • 151
  • 237
Amir Ziarati
  • 14,248
  • 11
  • 47
  • 52

1 Answers1

0

I found the problem. when i decompiled kotlin code bytecode i got this java code:

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();
  }
 }
}

as you see the variable changes to a private static. I just needed to use @JvmField to fix this issue and now the decompiled byte code is like below:

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();
  }
  }
  }
Amir Ziarati
  • 14,248
  • 11
  • 47
  • 52