What is the default target for an annotation when

2019-02-15 15:56发布

问题:

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.