Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get annotations of a Kotlin property from Java?

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?

like image 801
Ricardo Meneghin Filho Avatar asked Feb 12 '17 23:02

Ricardo Meneghin Filho


2 Answers

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());
like image 189
Alexander Udalov Avatar answered Nov 04 '22 12:11

Alexander Udalov


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) 
like image 41
Vince Avatar answered Nov 04 '22 12:11

Vince