Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reflect annotations in Scala 2.10?

I am trying to discover if a trait's value has an annotation associated to it. After reviewing the Scala 2.10-M7 reflection API I thought that the getAnnotations method (located in Symbol) could be a great candidate, but it is returning an empty list, as shown in the following REPL session:

scala> class W extends scala.annotation.Annotation
defined class W

scala> trait A { @W val a: Int }
defined trait A

scala> typeOf[A].members.last
res0: $r.intp.global.Symbol = value a

scala> res0.getAnnotations
res1: List[$r.intp.global.AnnotationInfo] = List()

Are those "annotations" the same annotations I am trying to deal with? How can I know if a is annotated with W?

like image 702
jeslg Avatar asked Sep 06 '12 15:09

jeslg


People also ask

Does Scala have reflection?

Scala reflection enables a form of metaprogramming which makes it possible for programs to modify themselves at compile time. This compile-time reflection is realized in the form of macros, which provide the ability to execute methods that manipulate abstract syntax trees at compile-time.

What is a reflection annotation?

Annotations are a kind of comment or meta data you can insert in your Java code. These annotations can then be processed at compile time by pre-compiler tools, or at runtime via Java Reflection. Here is an example of class annotation: @MyAnnotation(name="someName", value = "Hello World") public class TheClass { }

What are annotations 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.

How annotations are obtained at runtime by use of reflection?

We use the reflection API to get class and method information from where we can read information about annotation attached to the class or the method.


1 Answers

Looks like a bug: https://issues.scala-lang.org/browse/SI-6325

update. Actually it's not a bug, but a combination of non-obvious ways of how annotations work in Scala. There is a way to make abstract annotated vals in traits work as desired. Take a look at the discussion at the aforementioned links for more details.

like image 124
Eugene Burmako Avatar answered Oct 12 '22 17:10

Eugene Burmako