2016-11-04 71 views
0

全部:如何在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

它可以使用scala.tools.reflect.ToolBox來實現這一目標:

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

這將刺激使用所有字段(包括默認值)作爲案例類Table的結果。