Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create annotations and get them in scala

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?

like image 676
Freewind Avatar asked Mar 03 '11 05:03

Freewind


People also ask

What is annotation in Scala?

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.

Does order of annotations matter?

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.

What are annotations in API?

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.


2 Answers

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

like image 146
Veebs Avatar answered Sep 28 '22 09:09

Veebs


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
      ^
like image 22
Wilfred Springer Avatar answered Sep 28 '22 07:09

Wilfred Springer