简体   繁体   English

如何通过反射访问 kotlin 中的类型使用注释?

[英]How do I access type use annotations in kotlin through reflection?

A library I'm using utilises type use annotations to add constraints to variables.我正在使用的利用类型使用注释向变量添加约束。 For example, if you wanted a configurable opacity (in percent, represented by a float ), you'd annotate the float type:例如,如果您想要一个可配置的不透明度(以百分比表示,由float表示),您需要注释float类型:

public @Setting.Constrain.Range(min = 0, max = 1, step = 0.1) float opacity = 1f;

I could not get the same library to work on identical kotlin code.我无法让相同的库在相同的 kotlin 代码上工作。

To simplify the question, let's declare the annotation and usage ourselves:为了简化问题,让我们自己声明注解和用法:

@Target(ElementType.TYPE_USE)
@Retention(RetentionPolicy.RUNTIME)
public @interface JavaAnnot { }
public class TestJava {

    @JavaAnnot int a = 5;

    public static void main(String[] args) {
        System.out.println(TestJava.class.getDeclaredFields()[0].getAnnotatedType().isAnnotationPresent(JavaAnnot.class));
    }

}

Running TestJava#main yields true , indicating that the JavaAnnot annotation is present on the type.运行TestJava#main产生true ,表明JavaAnnot注释存在于该类型上。

If we introduce a new kotlin class TestKotlin with a similar a field and annotated type:如果我们引入一个新的 kotlin class TestKotlin具有类似a字段和注释类型:

class TestKotlin {

    val a: @JavaAnnot Int = 5

}

The previous check, now on the TestKotlin class:之前的检查,现在在TestKotlin class 上:

TestKotlin.class.getDeclaredField("a").getAnnotatedType().isAnnotationPresent(JavaAnnot.class)

yields false , indicating that the JavaAnnot annotation is NOT present on the Int type of a , even though we clearly did annotate it.产生false ,表明JavaAnnot注释不存在于Int类型的a上,即使我们清楚地对它进行了注释。

I've tried:我试过了:

  • Annotating a with @JvmField .@JvmField注释a This did not change the behaviour.这并没有改变行为。
  • Declaring an identical annotation in kotlin:在 kotlin 中声明一个相同的注解:
@Target(AnnotationTarget.TYPE)
@Retention(AnnotationRetention.RUNTIME)
annotation class KotlinAnnot
val a: @KotlinAnnot Int = 5

Did not fix the problem.没有解决问题。

  • Inspecting other metadata accessible through reflection: I did not find anything useful.检查可通过反射访问的其他元数据:我没有发现任何有用的东西。

Is this a kotlin bug?这是 kotlin 错误吗? Do type use annotations not exist in kotlin, or is the syntax different? kotlin 中不存在类型使用注释,还是语法不同? What am I doing wrong?我究竟做错了什么?

Thanks.谢谢。

Annotations of AnnotatedType of Kotlin fields are stored with Kotlin Metadata annotation and can be accessed only by Kotlin Reflection. Kotlin 字段的 AnnotatedType 注释与 Kotlin 元数据注释一起存储,只能通过 Kotlin 反射访问。

Update:更新:

Since Kotlin 1.4.0, the compiler writes type annotations as it is expected.从 Kotlin 1.4.0 开始,编译器按预期编写类型注释。

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

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