How to define and use custom annotations in Scala

前端 未结 2 1594
萌比男神i
萌比男神i 2021-02-20 04:28

I am trying use a custom annotation in Scala. In this example, I create a string that I want to annotate with metadata (in this case, another string). Then, given an instance of

2条回答
  •  無奈伤痛
    2021-02-20 05:11

    With scala 2.11.6, this works to extract values of a annotation:

    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
    }
    

提交回复
热议问题