[英]Scala 2.11 reflection and annotations (Java) with parameters
I have a simple class-level annotation written in Java: 我有一个用Java编写的简单的类级注释:
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface Collection {
String name();
}
used like: 像这样使用:
@Collection(name="mytable")
case class Foo(...)
I need to introspect classes in Scala 2.11 to obtain the value of the name parameter. 我需要自省Scala 2.11中的类以获取name参数的值。 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")
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. 我可以看到我的name参数及其值,但是似乎无法像Map或任何友好对象那样访问。 How can I get the value of my annotation's parameter? 如何获取注释参数的值?
树形api实现了将元素取出的产品,因此这是一个很烂的演示,但是您可以取出元素:
println(anno.tree.children.last.productElement(1)) // prints "mytable"
If you can handle using Jackson, then I'd re-use its annotation processing functionality instead of using scala reflection. 如果可以使用Jackson进行处理,那么我将重用其注释处理功能,而不是使用scala反射。
object Test {
@Collection(name="mytable")
case class Foo(bar: String)
def main(args: Array[String]): Unit = {
val introspector = new JacksonAnnotationIntrospector
val ac = AnnotatedClass.construct(classOf[Foo], introspector, null)
val annotation = ac.getAnnotations.get(classOf[Collection])
println(annotation.name())
}
}
If the class does not have the annotation then annotation
is null. 如果该类没有注释,则annotation
为null。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.