如果你真的想要的FieldName
我能想到的最好的實例是使用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] = [email protected]
scala> tb.eval(tb.untypecheck(annotation.tree)).asInstanceOf[FieldName]
res10: FieldName = FieldName(foo)
隨着.tree.children.tail
,您可以訪問傳遞給FieldName
的參數,而無需創建實際的實例。
scala> annotation.tree.children.tail.map{ case Literal(Constant(field)) => field }
res11: List[Any] = List(foo)
如果你只是希望所有FieldName
註解,並提取它們的價值,你可以這樣做:
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)
呀。哎呀。固定。 – Reactormonk