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

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

问题描述

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

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

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

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
}

背景

我正在尝试将Jongo作为Kotlin中的MongoDB客户端,并且在注释id字段时遇到问题。当它被注释时,Jongo没有正确映射id属性:

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

有问题的注释只是杰克逊的meta-annotations。但是,当我像这样注释属性时,它似乎有效,表明使用现场问题:

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

我希望 @field 是默认的使用网站,但它似乎不是。

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

推荐答案

参考说:


如果您未指定使用地点目标,则根据
选择目标到所使用注释的 @Target 注释。如果有多个适用目标的
,则使用以下
下列表中的第一个适用目标:

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 (构造函数参数)

  • property (具有此目标的注释对于Java)

  • 字段

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

因此,如果您的注释具有 @Target({ElementType.FIELD}),Kotlin中的注释将定位 @field :

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

如果没有指定 @Target ,它可以在任何程序元素上使用: @property:目标也适用,默认选择。

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天全站免登陆