【发布时间】:2020-09-24 04:21:49
【问题描述】:
我已经定义了一个简单的 scala 注释,并用它来注释我的案例类 Person:
package com.my
import scala.annotation.StaticAnnotation
@scala.annotation.meta.field
class Description(value: String) extends StaticAnnotation{
}
然后我在我的 Person 类中使用它:
package com.my
import scala.beans.BeanProperty
case class Person(
@Description(value = "name00")
name: String,
@Description(value = "age00")
age: Int,
@BeanProperty
xyz: String = "xyz"
)
object Person {
def main(args: Array[String]): Unit = {
val p = Person("abc", 21)
classOf[Person].getDeclaredFields.foreach {
field =>
field.setAccessible(true)
val name = field.getName
val value = field.get(p)
//annotations always return empty array
val annotations = field.getDeclaredAnnotations
annotations.foreach {
annotation =>
val tpe = annotation.annotationType()
println(tpe)
}
println(s"name is $name, value is: $value")
}
}
}
在Person对象的main方法中,注解数组始终为空, 请问如何获取字段上定义的注解信息。
【问题讨论】:
-
为什么需要这些注释?也许您可以以更简单/更清洁的方式解决您最初的问题。
-
Scala注解不同于Java注解,你使用Scala Reflection API来访问它们。
-
@LuisMiguelMejíaSuárez。我这里只是用这个简单的代码来说明我的问题,关键是我要使用scala注解,谢谢。
-
@Tom 为什么使用 Scala 注释很重要?你可以使用Java注解吗? (无论如何你使用 Java 反射,而不是 Scala 反射。)
-
@Tom 不管怎样,如果
@Description是 Scala 注释很重要,请查看我使用 Scala 反射的答案的更新。
标签: scala reflection annotations scala-reflect