How to define and use custom annotations in Scala

I am trying to use custom annotation in Scala. In this example, I am creating a row that I want to annotate with metadata (in this case, another row). Then, given the data instance, and I want to read the annotation.

scala> case class named(name: String) extends scala.annotation.StaticAnnotation defined class named scala> @named("Greeting") val v = "Hello" v: String = Hello scala> def valueToName(x: String): String = ??? valueToName: (x: String)String scala> valueToName(v) // returns "Greeting" 

Is it possible?

+5
source share
2 answers

With scala 2.11.6, this works to extract annotation values:

 case class Named(name: String) extends scala.annotation.StaticAnnotation val myAnnotatedClass: ClassSymbol = u.runtimeMirror(Thread.currentThread().getContextClassLoader).staticClass("MyAnnotatedClass") val annotation: Option[Annotation] = myAnnotatedClass.annotations.find(_.tree.tpe =:= u.typeOf[Named]) val result = annotation.flatMap { a => a.tree.children.tail.collect({ case Literal(Constant(name: String)) => doSomething(name) }).headOption } 
+2
source

Scala has several kinds of annotations:

Java annotations that you can access using the Java Reflection API, annotations that are only in the source code, static annotations available for type checking in different compilation units (so they should be somewhere in the class file, but not there normal reflections go) and classfile annotations, which are stored as java annotations but cannot be read using the java reflection api.

I described how to access static and classfile annotations here: What is the current state of scala reflection capabilities, especially wrt annotations since version 2.11?

If you just need an annotation containing a string using the Java annotation loaded by the JVM, you can be a simpler alternative.

+1
source

Source: https://habr.com/ru/post/1243094/


All Articles