Kotlin得到Field Annotation总是空的

时间:2017-10-01 13:37:58

标签: reflection annotations kotlin

我有以下Kotlin Annotation

SELECT *
FROM books AS b
JOIN structure AS s ON s.book_fk = b.id
AND s.book_version_nr =
(
    SELECT MAX(s2.book_version_nr)
    FROM structure AS s2
    WHERE s2.book_fk = b.id
)
JOIN articles AS a ON a.id = s.article_fk
JOIN article_texts AS as ON as.article_fk = a.id
AND as.version_nr = s.article_version_nr
AND as.language_fk = 'languageIdFromScript'
WHERE b.id = 'bookIdFromScript'
ORDER BY s.position ASC 

以下测试代码

@Target(AnnotationTarget.FIELD, AnnotationTarget.PROPERTY_GETTER)
@Retention(AnnotationRetention.RUNTIME)
annotation class Field(val value: String)

它将打印以下输出:

class TestObject(@field:Field("id") val id: Long) {

  @field:Field("string")
  val string = "Hello world"

  @get:Field("prop")
  val prop get() = string
}

class AnnotationTest {

  @Test
  fun test() {
    val obj = TestObject(200L)
    for (member in obj::class.declaredMemberProperties) {
      if (member.findAnnotation<Field>() != null) {
        println(member)
      }
      println(member)
      println(member.annotations)
    }
    println("#########")
    for(member in obj.javaClass.declaredFields) {
      println(member)
      println(member.annotations)
    }
  }

}

为什么我无法通过Kotlin反射看到注释?需要确定字段和属性getter上是否存在给定的注释。

1 个答案:

答案 0 :(得分:2)

<?php $str = 'Dlasdf234dkl sdfkl8886adaf15adfjk7 asdflkj376661a s445s198'; echo preg_replace_callback('~([0-9]{2,})~', function($matches) { return strrev($matches[1]); }, $str); // Dlasdf432dkl sdfkl6888adaf51adfjk7 asdflkj166673a s544s891 ?> 的注释是针对getter的,而不是在属性上调用prop,您必须在属性的getter上调用它。

findAnnotation

for (member in obj::class.declaredMemberProperties) { if (member.getter.findAnnotation<Field>() != null) { //add .getter println(member) } println(member) println(member.getter.annotations) //add .getter } id的注释是定位字段,因此您在第二个循环中所做的是正确的。由于string会返回member.annotations,因此您必须在打印前将其更改为Annotation[]

List

输出:

for(member in obj.javaClass.declaredFields) {
    println(member)
    println(member.annotations.toList())  //Add .toList()
}