Access package private method in Scala REPL

£可爱£侵袭症+ 提交于 2019-12-23 04:15:16

问题


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?


回答1:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!