What is the default target for an annotation when annotating property in Kotlin?

流过昼夜 提交于 2019-12-03 22:47:53

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/35361162/what-is-the-default-target-for-an-annotation-when-annotating-property-in-kotlin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!