简体   繁体   English

如何从Java获取Kotlin属性的注释?

[英]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: 我有一个kotlin类,其属性具有Java注释,但我无法使用Java反射访问这些注释:

class TestClass(@A var myProperty : String)

The following test prints null: 以下测试打印为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? 我怎样才能获得给定kotlin属性的注释?

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: 但是,如果您确实需要注释属性,可以通过Kotlin反射找到注释:

Field field = TestClass.class.getDeclaredField("field");
KProperty<?> property = ReflectJvmMapping.getKotlinProperty(f);
System.out.println(property.getAnnotations());

From the Kotlin reference : 来自Kotlin参考

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. 当您注释属性或主构造函数参数时,有多个Java元素是从相应的Kotlin元素生成的,因此生成的Java字节码中的注释有多个可能的位置。

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) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM