Access package private method in Scala REPL

大城市里の小女人 提交于 2019-12-06 18:59:27
Rich

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