我有一个kotlin类,其属性具有Java注释,但我无法使用Java反射访问这些注释:
class TestClass(@A var myProperty : String)
以下测试打印为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));
}
}
我怎样才能获得给定kotlin属性的注释?
2 回答
如另一个答案所述,您可能希望注释字段而不是属性 . 但是,如果您确实需要注释属性,可以通过Kotlin反射找到注释:
来自Kotlin reference:
在这种情况下,您要注释该字段,因此您的属性声明应如下所示:
你的构造函数看起来像: