Ric*_*lho 8 java reflection kotlin
我有一个kotlin类,其属性具有Java注释,但我无法使用Java反射访问这些注释:
class TestClass(@A var myProperty : String)
Run Code Online (Sandbox Code Playgroud)
以下测试打印为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));
}
}
Run Code Online (Sandbox Code Playgroud)
我怎样才能获得给定kotlin属性的注释?
正如另一个答案中提到的,您可能想要注释字段而不是属性.但是,如果您确实需要注释属性,可以通过Kotlin反射找到注释:
Field field = TestClass.class.getDeclaredField("field");
KProperty<?> property = ReflectJvmMapping.getKotlinProperty(f);
System.out.println(property.getAnnotations());
Run Code Online (Sandbox Code Playgroud)
来自Kotlin 参考:
当您注释属性或主构造函数参数时,会从相应的 Kotlin 元素生成多个 Java 元素,因此生成的 Java 字节码中的注释可能有多个位置。
在本例中,您想要注释该字段,因此您的属性声明应如下所示:
@field:A
Run Code Online (Sandbox Code Playgroud)
你的构造函数看起来像:
TestClass(@field:A myProperty : String)
Run Code Online (Sandbox Code Playgroud)