Skip to content

Instantly share code, notes, and snippets.

@snipsnipsnip
Last active August 24, 2019 15:55
Show Gist options
  • Save snipsnipsnip/365779 to your computer and use it in GitHub Desktop.
Save snipsnipsnip/365779 to your computer and use it in GitHub Desktop.
inspectable.scala: 3.methods foreach println
// originally from http://lousycoder.com/blog/index.php?/archives/91-Scala-Querying-an-objects-fields-and-methods-with-reflection.html
package inspectable
import scala.Console._
import scala.tools.nsc.util.NameTransformer._
import java.lang.reflect.Modifier._
import java.lang.reflect.{Method, Member, Field}
import java.lang.Class
object Inspectable
{
implicit def any2Inspectable(any : Any) = new Inspectable(any)
def apply(any : Any) = new Inspectable(any)
}
class Inspectable(any: Any)
{
def methods = members(_.getDeclaredMethods).
map(new InspectedMethod(_)).
filter(!_.toString.startsWith("$tag")).
sort(_.toString < _.toString) match {
case members =>
new InspectedList(members)
}
def fields = members(_.getDeclaredFields).
map(new InspectedField(_)).
filter(_.toString != "MODULE$").
sort(_.toString < _.toString) match {
case members =>
new InspectedList(members)
}
private def members[T <: Member](f : Class[_] => Iterable[T]) =
f(wrapped.getClass).toList.filter(m => !isPrivate(m.getModifiers))
private def wrapped : AnyRef = any 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 => x.asInstanceOf[AnyRef]
}
}
class InspectedList[T](list : Iterable[T]) extends Iterable[T]
{
override def elements = list elements
override def toString = list mkString "\n"
}
class InspectedMember(val member : Member)
{
protected def staticInfo =
if (isStatic(member.getModifiers)) " <static>" else ""
}
class InspectedMethod(method : Method) extends InspectedMember(method)
{
override def toString =
decode(method.toString.
replaceFirst("\\).*", ")").
replaceAll("[^(]+\\.", "").
replace("()", "")) +
" : " +
method.getReturnType.toString +
staticInfo
}
class InspectedField(field : Field) extends InspectedMember(field)
{
override def toString =
decode(field.toString.replaceFirst("^.*\\.", "")) +
" : " +
field.getType.toString +
staticInfo
}
scala> import inspectable.Inspectable._
scala> 3.methods foreach println
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment