I have a kotlin class whose properties have a Java annotation, but i can't acess these annotations with Java reflection:
class TestClass(@A var myProperty : String)
The following test prints null:
public class TestKotlinField {
@Retention(RetentionPolicy.RUNTIME)
public @interface A{}
@Test
public void test() throws NoSuchFieldException {
System.out.println(TestClass.class.getDeclaredField("myProperty").getAnnotation(A.class));
}
}
How can i get the annotations of a given kotlin property?
As mentioned in another answer, you probably want to annotate the field instead of the property. However, in case you really need to annotate the property, you can find the annotations via Kotlin reflection:
Field field = TestClass.class.getDeclaredField("field");
KProperty<?> property = ReflectJvmMapping.getKotlinProperty(f);
System.out.println(property.getAnnotations());
From the Kotlin reference:
When you're annotating a property or a primary constructor parameter, there are multiple Java elements which are generated from the corresponding Kotlin element, and therefore multiple possible locations for the annotation in the generated Java bytecode.
In this case, you want to annotate the field, so your property declaration should look like:
@field:A
Your constructor would look like:
TestClass(@field:A myProperty : String)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With