如何创建注释,并让他们在斯卡拉 [英] How to create annotations and get them in scala
问题描述
我要定义一些注释和Scala中使用它们。
I want to define some annotations and use them in Scala.
我看着斯卡拉的来源, scala.annotation
包中发现,有喜欢的 tailrec
注释部分,开关
, elidable
,等等。所以我定义了一些注解为他们做的:
I looked into the source of Scala, found in scala.annotation
package, there are some annotations like tailrec
, switch
, elidable
, and so on. So I defined some annotations as them do:
class A extends StaticAnnotation
@A
class X {
@A
def aa() {}
}
然后我写一个测试:
Then I write a test:
object Main {
def main(args: Array[String]) {
val x = new X
println(x.getClass.getAnnotations.length)
x.getClass.getAnnotations map { println }
}
}
它打印一些奇怪的信息:
It prints some strange messages:
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
。
我怎样才能在斯卡拉创建注释是否正确?以及如何使用,让他们?
How can I create annotations in Scala correctly? And how to use and get them?
推荐答案
难道有事情做保留?我敢打赌,@tailrec不包括在如何产生的字节code。
Could it have something to do with retention? I bet @tailrec is not included in the bytecode getting generated.
如果我试图扩展ClassfileAnnotation(以有保留运行时),斯卡拉告诉我,它无法做到的,它有在Java中做:
If I try to extend ClassfileAnnotation (in order to have runtime retention), Scala tells me that it can't be done, and it has to be done in 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
^
这篇关于如何创建注释,并让他们在斯卡拉的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!