ctran (owner)

Fork Of

gist: 87519 by retiman Scala reflection

Revisions

gist: 131273 Download_button fork
public
Public Clone URL: git://gist.github.com/131273.git
Embed All Files: show embed
reflection.scala #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import scala.Console._
import scala.tools.nsc.util.NameTransformer._
 
object ScalaReflection {
  implicit def any2anyExtras(x: Any) = new AnyExtras(x)
}
 
class AnyExtras(x: Any) {
  def methods_ = println(methods.reduceLeft[String](_ + ", " + _))
  def methods__ = methods.foreach(println _)
  def fields_ = println(fields.reduceLeft[String](_ + ", " + _))
  def fields__ = fields.foreach(println _)
  
  def methods = wrapped.getClass
      .getDeclaredMethods
      .toList
      .map(m => decode(m.toString
                        .replaceFirst("\\).*", ")")
                        .replaceAll("[^(]+\\.", "")
                        .replace("()", "")))
      .filter(!_.startsWith("$tag"))
  
  def fields = wrapped.getClass
      .getDeclaredFields
      .toList
      .map(m => decode(m.toString.replaceFirst("^.*\\.", "")))
 
  private def wrapped: AnyRef = x match {
    case x: Byte => byte2Byte(x)
    case x: Short => short2Short(x)
    case x: Char => char2Character(x)
    case x: Int => int2Integer(x)
    case x: Long => long2Long(x)
    case x: Float => float2Float(x)
    case x: Double => double2Double(x)
    case x: Boolean => boolean2Boolean(x)
    case _ => x.asInstanceOf[AnyRef]
  }
}