If you really want the instance of FieldName
the best I can think of is using a ToolBox
:
scala> case class FieldName(field: String) extends scala.annotation.StaticAnnotation
defined class FieldName
scala> @FieldName("foo") trait Foo
defined trait Foo
scala> import scala.reflect.runtime.universe._
import scala.reflect.runtime.universe._
scala> val annotation = symbolOf[Foo].annotations.head
annotation: reflect.runtime.universe.Annotation = FieldName("foo")
scala> import scala.tools.reflect.ToolBox
import scala.tools.reflect.ToolBox
scala> val tb = runtimeMirror(getClass.getClassLoader).mkToolBox()
tb: scala.tools.reflect.ToolBox[reflect.runtime.universe.type] = scala.tools.reflect.ToolBoxFactory$ToolBoxImpl@1b26a499
scala> tb.eval(tb.untypecheck(annotation.tree)).asInstanceOf[FieldName]
res10: FieldName = FieldName(foo)
With .tree.children.tail
you can access the arguments passed to FieldName
without creating the actual instance.
scala> annotation.tree.children.tail.map{ case Literal(Constant(field)) => field }
res11: List[Any] = List(foo)
If you just want all FieldName
annotations and extract their value, you can do this:
scala> val fields = symbolOf[Foo].annotations.withFilter(
| a => a.tree.tpe <:< typeOf[FieldName]
| ).flatMap(
| a => a.tree.children.tail.map{ case Literal(Constant(field)) => field }
| )
fields: List[Any] = List(foo)