如何创建注释并在 Scala 中获取它们 [英] How to create annotations and get them in scala
问题描述
我想定义一些注解并在 Scala 中使用它们.
I want to define some annotations and use them in Scala.
我查看了 Scala 的源代码,在 scala.annotation
包中找到了一些注释,例如 tailrec
、switch
、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() {}
}
然后我写一个测试:
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
.
如何在 Scala 中正确创建注释?以及如何使用和获取它们?
How can I create annotations in Scala correctly? And how to use and get them?
推荐答案
是否与保留有关?我敢打赌 @tailrec 不包含在生成的字节码中.
Could it have something to do with retention? I bet @tailrec is not included in the bytecode getting generated.
如果我尝试扩展 ClassfileAnnotation(为了有运行时保留),Scala 告诉我它不能完成,必须在 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
^
这篇关于如何创建注释并在 Scala 中获取它们的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!