Fre*_*ind 17 annotations scala
我想定义一些注释并在Scala中使用它们.
我看着斯卡拉的来源,发现scala.annotation包,有喜欢的一些注释tailrec,switch,elidable,等等.所以我定义了一些注释:
class A extends StaticAnnotation
@A
class X {
@A
def aa() {}
}
Run Code Online (Sandbox Code Playgroud)
然后我写了一个测试:
object Main {
def main(args: Array[String]) {
val x = new X
println(x.getClass.getAnnotations.length)
x.getClass.getAnnotations map { println }
}
}
Run Code Online (Sandbox Code Playgroud)
它打印一些奇怪的消息:
1
@scala.reflect.ScalaSignature(bytes=u1" !1* 1!AbCaE
9"a!Q!! 1gn!!.<b iBPE*,7
Ii#)1oY1mC&1'G.Y(cUGCa#=S:LGO/AA!A 1mI!)
Run Code Online (Sandbox Code Playgroud)
似乎我无法获得注释aaa.A.
如何在Scala中正确创建注释?以及如何使用和获取它们?
Vee*_*ebs 16
FWIW,您现在可以在scala 2.10中定义scala注释并使用反射来读取它们.
以下是一些示例: 反映Scala 2.10中的注释
它可能与保留有关吗?我打赌@tailrec不包含在生成的字节码中.
如果我尝试扩展ClassfileAnnotation(为了具有运行时保留),Scala告诉我它无法完成,而且必须在Java中完成:
./test.scala:1: warning: implementation restriction: subclassing Classfile does not
make your annotation visible at runtime. If that is what
you want, you must write the annotation class in Java.
class A extends ClassfileAnnotation
^
Run Code Online (Sandbox Code Playgroud)