/src/main/scala/awesome/Util.scala

https://github.com/stevej/awesome · Scala · 51 lines · 36 code · 9 blank · 6 comment · 3 complexity · e1024584f795333323fc55fb265df622 MD5 · raw file

  1. package awesome
  2. import java.lang.reflect
  3. import reflect.{ Proxy, InvocationHandler }
  4. /** Misc dumping ground for bits in progress */
  5. object Util {
  6. // implicit def br(xs: Seq[Byte]) = new parser.ByteReader(xs)
  7. // def parse(xs: Seq[Byte])(p: ScalaSigParser => ScalaSigParser#Parser[_]) = p(new ScalaSigParser())(br(xs))
  8. /** Usage: singleton[Set.type] */
  9. def singleton[T](implicit man: Manifest[T]) = {
  10. val name = man.erasure.getName()
  11. assert(name endsWith "$", "Not an object: " + name)
  12. val clazz = forName(name)
  13. clazz.getField("MODULE$").get(clazz).asInstanceOf[T]
  14. }
  15. /** proxy experiments */
  16. def walkInterfaces(xs: List[JClass[_]]): List[JClass[_]] = {
  17. val xs2 = xs flatMap (_.getInterfaces)
  18. if ((xs2.toSet -- xs.toSet).nonEmpty) walkInterfaces((xs ++ xs2).distinct)
  19. else xs
  20. }
  21. def proxy[T <: AnyRef](x: T) = {
  22. val clazz = x.getClass
  23. val interfaces = walkInterfaces(clazz.getInterfaces.toList)
  24. val handler = new reflect.InvocationHandler {
  25. def invoke(proxy: Object, method: reflect.Method, args: Array[Object]): Object = {
  26. method.invoke(x, args: _*)
  27. }
  28. }
  29. reflect.Proxy.newProxyInstance(clazz.getClassLoader, Array[Class[_]](interfaces: _*), handler)
  30. }
  31. def unproxy(x: AnyRef) = reflect.Proxy.getInvocationHandler(x)
  32. /** More useful stack traces */
  33. case class StackElement(className: String, fileName: String, lineNumber: Int, methodName: String) { }
  34. def stackElements: List[StackElement] = {
  35. val elems = new Exception().getStackTrace.toList
  36. elems map (x => StackElement(x.getClassName, x.getFileName, x.getLineNumber, x.getMethodName))
  37. }
  38. def stackFilenames = stackElements map (_.fileName) distinct
  39. def stackClassnames = stackElements map (_.className) distinct
  40. def stackClazzes = stackClassnames flatMap forNameOpt
  41. def stackClazzes2 = Stream from 0 map sun.reflect.Reflection.getCallerClass takeWhile (_ != null) toList
  42. }