如何在 Scala 程序中反映字段注释 (Java)? [英] How can I reflect on a field annotation (Java) in a Scala program?

查看:15
本文介绍了如何在 Scala 程序中反映字段注释 (Java)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是 Scala 2.13,我知道自旧版本以来已经弃用了很多.

I'm using Scala 2.13 and I know there's been a lot deprecated since older versions.

我有这个注释:

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

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

(I know... I've got lots of ElementTypes there, but I'm struggling to see where this pops up in reflection so wanted to maximize my chances of a hit!)

像这样使用:

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

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

How can I reflect on this to get the my Java Annotation (Foo), so I can 1) know whether @Foo exists on a given field, and 2) get the index value. Note I have a declared default value for Foo.index that may be overridden at runtime, so this is a runtime-scoped annotation.

推荐答案

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

Here is solution using Java reflection.

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

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

对于@(Foo @getter)(index = 3) age: 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 do

For @(Foo @param)(index = 3) age: Int or just @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.

You can combine meta-annotations @field, @getter, @param.

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

I guess similar thing can be done with Scala reflection.

这篇关于如何在 Scala 程序中反映字段注释 (Java)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆