0
如何獲得具有默認值註釋的註釋對象?
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()