Suppose I have a private[stuff]
method Stuff.something
in org.my.stuff
. Is there something that I can do in the Scala REPL so that I can call Stuff.something
without getting the error error: value something is not a member of org.my.stuff.Stuff
?
In particular, can I get the REPL to be "inside" a given package (here org.my.stuff
), giving access to its private members?
Using "packages" in the REPL
You cannot get a REPL prompt "inside" a given package, see https://stackoverflow.com/a/2632303/8261
You can use "package" statements inside ":paste -raw
" mode in the REPL (see e.g. http://codepodu.com/paste-mode-in-scala-repl/ for docs)
For example, if you had code like:
package org.my.stuff {
object Stuff {
private[stuff] val something = "x"
}
}
You could declare a helper class in the same package using ":paste -raw
" mode, i.e.
scala> :paste -raw
// Entering paste mode (ctrl-D to finish)
package org.my.stuff {
object StuffAccessHelper {
def something = Stuff.something
}
}
// Exiting paste mode, now interpreting.
scala> org.my.stuff.StuffAccessHelper.something
res11: String = x
How to access any members using setAccessible
You can always fall back on the full "setAccessible
" reflection incantation, as described at How do I read a private field in Java?
Using the same prior code as above, you can access org.my.stuff.Stuff.something
like:
scala> val f = org.my.stuff.Stuff.getClass.getDeclaredField("something")
f: java.lang.reflect.Field = private final java.lang.String org.my.stuff.Stuff$.something
scala> f.setAccessible(true)
scala> f.get(org.my.stuff.Stuff)
res10: Object = x
来源:https://stackoverflow.com/questions/42068129/access-package-private-method-in-scala-repl