Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save matthandlersux/3727613 to your computer and use it in GitHub Desktop.
Save matthandlersux/3727613 to your computer and use it in GitHub Desktop.

Revisions

  1. @jorgeortiz85 jorgeortiz85 revised this gist Mar 2, 2012. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion PrivateMethodCaller.scala
    Original file line number Diff line number Diff line change
    @@ -14,7 +14,7 @@ class PrivateMethodCaller(x: AnyRef, methodName: String) {
    }

    class PrivateMethodExposer(x: AnyRef) {
    def apply(method: Symbol): PrivateMethodCaller = new PrivateMethodCaller(x, method.name)
    def apply(method: scala.Symbol): PrivateMethodCaller = new PrivateMethodCaller(x, method.name)
    }

    def p(x: AnyRef): PrivateMethodExposer = new PrivateMethodExposer(x)
  2. @jorgeortiz85 jorgeortiz85 created this gist Apr 7, 2011.
    20 changes: 20 additions & 0 deletions PrivateMethodCaller.scala
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,20 @@
    // Usage:
    // p(instance)('privateMethod)(arg1, arg2, arg3)

    class PrivateMethodCaller(x: AnyRef, methodName: String) {
    def apply(_args: Any*): Any = {
    val args = _args.map(_.asInstanceOf[AnyRef])
    def _parents: Stream[Class[_]] = Stream(x.getClass) #::: _parents.map(_.getSuperclass)
    val parents = _parents.takeWhile(_ != null).toList
    val methods = parents.flatMap(_.getDeclaredMethods)
    val method = methods.find(_.getName == methodName).getOrElse(throw new IllegalArgumentException("Method " + methodName + " not found"))
    method.setAccessible(true)
    method.invoke(x, args : _*)
    }
    }

    class PrivateMethodExposer(x: AnyRef) {
    def apply(method: Symbol): PrivateMethodCaller = new PrivateMethodCaller(x, method.name)
    }

    def p(x: AnyRef): PrivateMethodExposer = new PrivateMethodExposer(x)