带有参数的 Scala 2.11 反射和注释(Java) [英] Scala 2.11 reflection and annotations (Java) with parameters
问题描述
我有一个用 Java 编写的简单类级注释:
I have a simple class-level annotation written in Java:
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface Collection {
String name();
}
用于:
@Collection(name="mytable")
case class Foo(...)
我需要内省 Scala 2.11 中的类以获取 name 参数的值.我怎样才能得到这些信息?我到此为止:
I need to introspect classes in Scala 2.11 to obtain the value of the name parameter. How can I get this info? I'm up to here:
val sym = currentMirror.classSymbol(Class.forName(fullName))
val anno = sym.annotations.head
val annoType = anno.tree.tpe // I can get this...works
println(anno.tree.children.tail) // prints List(name = "mytable")
我很接近!我可以看到我的 name 参数及其值,但这似乎不像 Map 或任何友好的东西那样可以访问.如何获取注释参数的值?
I'm close! I can see my name parameter and its value but this doesn't seem to be accessible like a Map or anything friendly. How can I get the value of my annotation's parameter?
推荐答案
tree api 实现了 product 来获取元素,所以这有点像hacky 演示,但是你可以获取你的元素:
The tree api implements product to get elements out, so this is kind of a hacky demonstration, but you can get out your element:
println(anno.tree.children.last.productElement(1)) // prints "mytable"
这篇关于带有参数的 Scala 2.11 反射和注释(Java)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!