在 Kotlin 中注释属性时,注释的默认目标是什么? [英] What is the default target for an annotation when annotating property in Kotlin?

查看:28
本文介绍了在 Kotlin 中注释属性时,注释的默认目标是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Kotlin 中的注释可以有不同的使用站点目标,如下所述:https://kotlinlang.org/docs/reference/annotations.html#annotation-use-site-targets

我的问题是:当未明确定义 use-site 时,在如下示例中注释类中的属性时的默认目标是什么?

class 测试 {@SomeAnnotationvar someProperty: 字符串?= 空}

背景

我正在 Kotlin 中尝试将 Jongo 作为 MongoDB 客户端,但在注释 id 字段时遇到问题.当像这样注释时,Jongo 没有正确映射 id 属性:

@MongoId @MongoObjectId var id: String?= 空

有问题的注释只是 Jackson 的元注释.但是,当我像这样注释属性时,它似乎可以工作,表明使用站点问题:

@field:[MongoId MongoObjectId]var id:字符串?= 空

我希望 @field 是默认使用站点,但似乎不是.

解决方案

参考 说:

<块引用>

如果不指定使用站点目标,则根据目标选择目标到正在使用的注释的 @Target 注释.如果有多个适用目标,第一个适用目标使用以下列表:

  • param(构造函数参数)
  • property(带有此目标的注释对 Java 不可见)
  • 字段

因此,如果您的注解具有 @Target({ElementType.FIELD}),则 Kotlin 中的注解将针对 @field:.

如果它没有指定 @Target,它可以用于任何程序元素:@property: 目标也适用并且默认选择.>

Annotations in Kotlin can have different use-site targets as explained here: https://kotlinlang.org/docs/reference/annotations.html#annotation-use-site-targets

My question is: When use-site is not explicitly defined, what is the default target when annotating property in a class like in the example below?

class Test {
  @SomeAnnotation
  var someProperty: String? = null
}

Background

I'm trying Jongo as MongoDB client in Kotlin and have problems annotating id field. Jongo does not map id property correctly when it's annotated like this:

@MongoId @MongoObjectId var id: String? = null

The annotations in question are just meta-annotations for Jackson. However it seems to work when I annotate the property like this, indicating use-site problem:

@field:[MongoId MongoObjectId]
var id: String? = null

I would expect that @field is default use-site, but it seems that it isn't.

解决方案

The reference says:

If you don’t specify a use-site target, the target is chosen according to the @Target annotation of the annotation being used. If there are multiple applicable targets, the first applicable target from the following list is used:

  • param (constructor parameter)
  • property (annotations with this target are not visible to Java)
  • field

So if your annotation has @Target({ElementType.FIELD}), the annotation in Kotlin will target @field:.

If it has no @Target specified, it may be used on any program element: the @property: target is also applicable and is chosen by default.

这篇关于在 Kotlin 中注释属性时,注释的默认目标是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆