繁体   English   中英

如何在 Scala 程序中反映字段注释 (Java)?

[英]How can I reflect on a field annotation (Java) in a Scala program?

我正在使用 Scala 2.13,并且我知道自旧版本以来已经弃用了很多。

我有这个注释:

@Inherited
@Target({ElementType.PARAMETER, ElementType.METHOD, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Foo {
    int index() default 0;
}

(我知道......我有很多 ElementTypes,但我很难看到它在反射中出现的位置,所以想最大限度地提高我的命中机会!)

像这样使用:

case class Person(name: String, @Foo(index = 3) age: Int)
val p = Person("Fred", 29)

我如何反思以获取我的 Java 注释(Foo),以便我可以 1)知道给定字段中是否存在 @Foo,以及 2)获取索引值。 注意我为 Foo.index 声明了一个默认值,它可能在运行时被覆盖,所以这是一个运行时范围的注释。

这是使用 Java 反射的解决方案。

对于@(Foo @field)(index = 3) age: Int do

println(classOf[Person].getDeclaredFields.map(_.getDeclaredAnnotationsByType(classOf[Foo]).map(_.index)).deep)
//Array(Array(), Array(3))

对于@(Foo @getter)(index = 3) age: Int do

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 do

println(classOf[Person].getDeclaredConstructors.map(_.getParameters.map(_.getDeclaredAnnotationsByType(classOf[Foo]).map(_.index))).deep)
//Array(Array(Array(), Array(3)))

您可以组合元注释@field@getter@param

我想类似的事情可以用 Scala 反射来完成。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM