Created
January 9, 2010 15:05
-
-
Save retronym/272933 to your computer and use it in GitHub Desktop.
Reflection Based toString
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import util.NameTransformer | |
| def unfold[A](a: A, f: A => Option[A]): Stream[A] = { | |
| Stream.cons(a, f(a).map(unfold(_, f)).getOrElse(Stream.empty)) | |
| } | |
| def get[T](f: java.lang.reflect.Field, a: AnyRef): T = { | |
| f.setAccessible(true) | |
| f.get(a).asInstanceOf[T] | |
| } | |
| def classAndSuperClasses(c: Class[_]): Stream[Class[_]] = unfold[Class[_]](c, (c) => Option(c.getSuperclass)) | |
| def showReflect(a: AnyRef): String = { | |
| val fields = classAndSuperClasses(a.getClass).flatMap(_.getDeclaredFields).filterNot(_.isSynthetic) | |
| fields.map((f) => NameTransformer.decode(f.getName) + "=" + get(f, a)).mkString(",") | |
| } | |
| // TEST | |
| trait T { | |
| val t1 = "t1" | |
| } | |
| class Base(val foo: String, val ?? : Int) { | |
| } | |
| class Derived(val d: Int) extends Base("foo", 1) with T | |
| assert(showReflect(new Derived(1)) == "t1=t1,d=1,??=1,foo=foo") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment