如何在scala中使用默认值获取注释

时间:2016-11-04 08:11:20

标签: scala

全部:

如何获取具有注释默认值的注释对象?

import scala.annotation.StaticAnnotation
import scala.reflect.runtime._
import scala.reflect.runtime.universe._

// The annotation has default value
case class Table(idField: String = "") extends StaticAnnotation

@Table()
case class SomeEntity()


println(getClassAnnotation[Table](classOf[SomeEntity]).idField)

def getClassAnnotation[A: TypeTag](beanClazz: Class[_]): A = {
  val typeAnnotation=currentMirror.typeOf[A]
  currentMirror.classSymbol(beanClazz).toType.typeSymbol.asClass.annotations.find(a => a.tree.tpe == typeAnnotation).map {
    annotation =>
      val value = annotation.tree.children.tail.map(_.productElement(0).asInstanceOf[Constant].value)
      currentMirror.reflectClass(typeAnnotation.typeSymbol.asClass).
        reflectConstructor(typeAnnotation.decl(termNames.CONSTRUCTOR).asMethod)(value: _*)
  }.get.asInstanceOf[A]
}

错误是

java.lang.ClassCastException: scala.reflect.internal.Trees$Select cannot be cast to scala.reflect.api.Constants$ConstantApi

如果覆盖值将通过,就像这样

@Table(idField="code")
case class SomeEntity()

1 个答案:

答案 0 :(得分:1)

可以使用scala.tools.reflect.ToolBox来实现这一目标:

import scala.tools.reflect.ToolBox
val tb = currentMirror.mkToolBox()
val result = tb.eval(tb.untypecheck(annotation.tree)).asInstanceOf[Table]

这将生成包含所有字段的案例类Table的结果,包括默认值。