這可以用TypeTag
來完成,通過您的輸入型的members
過濾:
import reflect.runtime.universe._
def listProperties[T: TypeTag]: List[(TermSymbol, Annotation)] = {
// a field is a Term that is a Var or a Val
val fields = typeOf[T].members.collect{ case s: TermSymbol => s }.
filter(s => s.isVal || s.isVar)
// then only keep the ones with a MyProperty annotation
fields.flatMap(f => f.annotations.find(_.tpe =:= typeOf[MyProperty]).
map((f, _))).toList
}
然後:
scala> class A { @MyProperty("") val a = 1 ; @MyProperty("a") var b = 2 ;
var c: Long = 1L }
defined class A
scala> listProperties[A]
res15: List[(reflect.runtime.universe.TermSymbol, reflect.runtime.universe.Annotation)]
= List((variable b,MyProperty("a")), (value a,MyProperty("")))
這不會給你直接MyProperty
而是universe.Annotation
。它有一個scalaArgs
方法,如果你需要做一些事情,你可以訪問它的參數樹。