在 Scala REPL 中访问包私有方法 [英] Access package private method in Scala REPL
问题描述
假设我在 org.my.stuff
中有一个 private[stuff]
方法 Stuff.something
.有什么我可以在 Scala REPL 中做的事情,这样我就可以调用 Stuff.something
而不会出现错误 error: value something is not a member of org.my.stuff.Stuff代码>?
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
?
特别是,我能否将 REPL 置于给定包的内部"(此处为 org.my.stuff
),从而可以访问其私有成员?
In particular, can I get the REPL to be "inside" a given package (here org.my.stuff
), giving access to its private members?
推荐答案
在 REPL 中使用包"
您无法在给定包的内部"获得 REPL 提示,请参阅 https://stackoverflow.com/a/2632303/8261
您可以在 REPL 中的:paste -raw
"模式中使用package"语句(参见例如 http://codepodu.com/paste-mode-in-scala-repl/ 文档)
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"
}
}
您可以使用:paste -raw
"模式在同一个包中声明一个辅助类,即
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
如何使用 setAccessible
访问任何成员您始终可以使用完整的setAccessible
"反射咒语,如如何在 Java 中读取私有字段?
使用与上面相同的先前代码,您可以访问org.my.stuff.Stuff.something
,例如:
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
这篇关于在 Scala REPL 中访问包私有方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!