反射初体验

参考文献

《thinking in scala 》- bruce & dianne

场景

scala中反射的初体验 - 编写一个工具类:优雅的输出类名及相关信息。

实验

package Simple
/**
  * Created by pengyucheng on 4/5/16.
  *
  * function: Pretty Class name Generator Utils
  */
import scala.reflect.runtime.currentMirror

object Name{
  def className(o:Any)= currentMirror.reflect(o).symbol.toString.replace('$',' ').split(' ').last
}
trait Name {
  override def toString = Name.className(this) // call the companion object's className(o)methoid
}

class ClassNameSeeker extends Name{}

class ClassNameSeeker2(label:String) extends Name{
  override def toString()= s"${super.toString} $label" // s"${expression} $var" 
}

class Test
  object test{
    def main(args: Array[String]) {
      // original Class Name
      println(new Test)

      // pretty and short Class Name
      val sns = new ClassNameSeeker //
      println(sns)

      // detail Class Name
      val sns2 = new ClassNameSeeker2("sparker") // detail message
      println(sns2)
    }
}

结果

Simple.Test@1bb089b
ClassNameSeeker
ClassNameSeeker2 sparker

你可能感兴趣的:(反射初体验)