Created
April 7, 2011 15:41
-
-
Save jorgeortiz85/908035 to your computer and use it in GitHub Desktop.
Calling private methods in Scala
This file contains 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
// 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: scala.Symbol): PrivateMethodCaller = new PrivateMethodCaller(x, method.name) | |
} | |
def p(x: AnyRef): PrivateMethodExposer = new PrivateMethodExposer(x) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
some method names are of the form:
org$apache$spark$sql$execution$command$ShowCreateTableCommand$$escapeSingleQuotedString
Workaround like so: