2015-02-10 61 views
5

我想(靜態)反映樣本類是這樣的:在scala 2.11中反映case class字段的最佳方法是什麼?

case class Foo[T,U](stuff:T, more:U, age:Int) { 
    val ignore:Boolean = false 
} 

我開始是這樣的:

val symbol = currentMirror.classSymbol(clazz) // symbol is universe.ClassSymbol 
// I want to know about type placeholders T and U 
val typeParamArgs = symbol.typeParams.map(tp => tp.name.toString) 
if(symbol.isCaseClass) { 
    val tsig = symbol.typeSignature 
    println(tsig) 
} 

好吧,在這一點上,如果我打印TSIG我看到:

[T, U]scala.AnyRef 
     with scala.Product 
     with scala.Serializable { 
    val stuff: T 
    private[this] val stuff: T 
    val more: U 
    private[this] val more: U 
    val age: scala.Int 
    private[this] val age: scala.Int 
    def <init>(stuff: T,more: U,age: scala.Int): co.blocke.Foo[T,U] 
    val ignore: scala.Boolean 
    private[this] val ignore: scala.Boolean 
    def copy[T, U](stuff: T,more: U,age: scala.Int): co.blocke.Foo[T,U] 
    def copy$default$1[T, U]: T @scala.annotation.unchecked.uncheckedVariance 
    def copy$default$2[T, U]: U @scala.annotation.unchecked.uncheckedVariance 
    def copy$default$3[T, U]: scala.Int @scala.annotation.unchecked.uncheckedVariance 
    override def productPrefix: java.lang.String 
    def productArity: scala.Int 
    def productElement(x$1: scala.Int): scala.Any 
    override def productIterator: Iterator[scala.Any] 
    def canEqual(x$1: scala.Any): scala.Boolean 
    override def hashCode(): scala.Int 
    override def toString(): java.lang.String 
    override def equals(x$1: scala.Any): scala.Boolean 
} 

看到中間那條線<init>?這是我想要反思的聲明。它有我需要的。

我該如何區分tsig(universe.Type)以獲得有關< init的信息>?(我不想對「忽略」的信息。)

回答

3

而是檢查類的.typeSignature,檢查構造函數的類型簽名與.primaryConstructor.typeSignature的:

val csig = symbol.primaryConstructor.typeSignature 
val params = csig.paramLists.head // paramLists returns a List of Lists 

這給你的參數列表的主要構造函數,因此您可以查詢名稱,類型等:

scala> params(1).name 
res47: reflect.runtime.universe.Symbol#NameType = more 

scala> params(2).typeSignature 
res48: reflect.runtime.universe.Type = scala.Int 
相關問題