可能重复的注解:
How to create annotations and get them in scala如何获取斯卡拉类字段
其他例子得到一个注解类的注释。我想这样做是为了得到一个类字段的注解(在本次测试版本),像这样:
import java.lang.annotation.{RetentionPolicy, Retention}
import annotation.meta.field
class AttribField() extends scala.annotation.StaticAnnotation
object MyTypes { type Attrib = AttribField @field }
import MyTypes._
case class TestClass(@Retention(RetentionPolicy.RUNTIME)
@Attrib version: Option[String])
object TestMe {
def main(args: Array[String]) {
val testObj = new TestClass(version = Some("1"))
testObj.getClass.getDeclaredFields.foreach(field => {
field.setAccessible(true)
println("field: name=" + field.getName + " value=" + field.get(testObj))
field.getAnnotations.foreach(x => println("x="+x)) // nothing in here
field.getDeclaredAnnotations.foreach(x => println("y="+x)) // nothing in here
// does not even compile
// field.getAnnotation(classOf[AttribField])
})
}
}
我要测试是否有一定的批注,则分支。 但我无法过关。必须有一些我错过的基础知识,但是什么?
1)现在的问题不是关于如何注释一个类中如何创建注释,并让他们在斯卡拉。 2)Danyel的答案越来越接近了,我想。但我必须承认,像我这样的基本编码器我绝不会猜到,要使注解变得如此复杂。 据我所知,他们的目的是帮助“getAnnotation”会做我, ,但要诠释universe.type#注释,好吧来吧... 仍然无法确定版本是否有注释。 – user2036540
你真的读过它吗?我链接到的问题解释了为什么它不起作用,以及如何通过在java中声明注释来解决它,这是2.10之前的唯一解决方案,并且很可能是很多人在2.10中做的。如果您使用的是java反射,它也是** only **解决方案。 –