I want to define some annotations and use them in Scala.
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!)
Seems I can't get the annotation aaa.A
.
How can I create annotations in Scala correctly? And how to use and get them?
Scala Annotations are metadata added to the program source code. Annotations are allowed on any kind of definition or declaration including vals, vars, classes, objects, traits, defs and types. Annotations are used to associate meta-information with definitions.
In almost all cases the answer is No, the order has no effect. But in fact it is a bit more complicated. Considering annotations that are processed by annotation processors, it was already stated in the other answers that it more depends on the order in which the processors run.
Annotations are like meta-tags that you can add to the code and apply to package declarations, type declarations, constructors, methods, fields, parameters, and variables.
FWIW, you can now define scala annotation in scala 2.10 and use reflection to read them back.
Here are some examples: Reflecting Annotations in Scala 2.10
Could it have something to do with retention? I bet @tailrec is not included in the bytecode getting generated.
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
^
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With