我想定义一些注释并在Scala中使用它们。
我查看了Scala的源代码,在scala.annotation
包中找到了一些注释,比如tailrec
、switch
、elidable
等等。因此,我定义了一些注释:
class A extends StaticAnnotation
@A
class X {
@A
def aa() {}
}
然后我写一个测试:
object Main {
def main(args: Array[String]) {
val x = new X
println(x.getClass.getAnnotations.length)
x.getClass.getAnnotations map { println }
}
}
它打印一些奇怪的消息:
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!)
似乎我无法获得注解aaa.A
。
如何在Scala中正确创建批注?以及如何使用和获取它们?
发布于 2011-03-03 06:06:41
这会不会与留存有关?我敢打赌,生成的字节码中没有包含@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
^
发布于 2013-02-01 23:29:23
FWIW,你现在可以在Scala2.10中定义scala注解,并使用反射来读回它们。
发布于 2011-03-03 07:11:46
我认为你现在只能在Java中定义注解。
https://stackoverflow.com/questions/5177010
复制