我使用的是 Scala 2.13,我知道自旧版本以来,有很多内容已被弃用。
我有这个注释:
@Inherited
@Target({ElementType.PARAMETER, ElementType.METHOD, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Foo {
int index() default 0;
}
(我知道...我那里有很多 ElementType,但我很难看到它在反射中出现在哪里,因此希望最大限度地提高命中的机会!)
像这样使用:
case class Person(name: String, @Foo(index = 3) age: Int)
val p = Person("Fred", 29)
我如何反射(reflect)这一点以获得我的Java注释(Foo),这样我就可以1)知道@Foo是否存在于给定字段上,2)获取索引值。请注意,我为 Foo.index 声明了一个默认值,该值可能会在运行时被覆盖,因此这是一个运行时范围的注释。
最佳答案
这是使用 Java 反射的解决方案。
对于 @(Foo @field)(index = 3) 年龄:Int
执行
println(classOf[Person].getDeclaredFields.map(_.getDeclaredAnnotationsByType(classOf[Foo]).map(_.index)).deep)
//Array(Array(), Array(3))
对于 @(Foo @getter)(index = 3) 年龄:Int
执行
println(classOf[Person].getDeclaredMethods.map(_.getDeclaredAnnotationsByType(classOf[Foo]).map(_.index)).deep)
//Array(Array(), Array(), Array(3), Array(), Array(), Array(), Array(), Array(), Array(), Array(), Array(), Array(), Array())
对于 @(Foo @param)(index = 3) Age: Int
或只是 @Foo(index = 3) Age: Int
执行
println(classOf[Person].getDeclaredConstructors.map(_.getParameters.map(_.getDeclaredAnnotationsByType(classOf[Foo]).map(_.index))).deep)
//Array(Array(Array(), Array(3)))
您可以组合元注释@field
、@getter
、@param
。
我想使用 Scala 反射也可以完成类似的事情。
关于java - 如何在 Scala 程序中反射(reflect)字段注释 (Java)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59620528/