如何在 REPL 中使用具有默认(包)或私有访问级别的成员? [英] How to use members with default (package) or private access level in REPL?

查看:39
本文介绍了如何在 REPL 中使用具有默认(包)或私有访问级别的成员?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图为我的测试/调试周期添加一些交互性,所以我尝试使用 Scala REPL 中的类.这很好用,但缺点是我无法访问包级别和私有级别的成员,可以从单元测试中对其进行测试(如果测试在同一个包中).

I was trying to add some interactivity to my test/debug cycle, so I tried playing around with my classes from the Scala REPL. This works great but has the disadvantage that I cannot access package- and private-level members, that can be tested from a unit test (if the test is in the same package).

我可以设置"Scala REPL 的包上下文"吗?

Can I "set" the package "context" of the Scala REPL?

我想我可以使用反射来访问成员,但是输入太多会破坏使用 REPL 的初衷.

I guess I could use reflection to access the members, but that's so much typing it would defeat the purpose of using the REPL in the first place.

推荐答案

我假设您正在测试的类是用 Java 编写的,因为您必须不遗余力地在 Scala 中创建仅包成员.

I assume the class you are testing are written in Java as you have to go out of your way to create package only member in Scala.

简而言之,这是不可能的.REPL 中的每一行都包含在它自己的包中,因此不允许从任何其他包访问另一个仅限包的成员.即使有一个未公开的系统属性来更改用于包装的默认包名前缀,包名仍然是通过增加一个数字自动生成的:

In short, it's not possible. Each line in the REPL is wrapped into it's own package, so it won't be allowed to access another package-only member from any other package. Even though there is an undocumented system property to change the default package name prefix used for wrapping, the package name is still generated automatically by incrementing a number:

$ scala -Xprint:parser -Dscala.repl.naming.line=foo.line
scala> val x = 1
[[syntax trees at end of parser]]// Scala source: <console>
package foo.line1 {
  object $read extends scala.ScalaObject {
    // snip ...
    object $iw extends scala.ScalaObject {
      // snip ...
      object $iw extends scala.ScalaObject {
        // snip ...
        val x = 1
      }
    }
  }

假设这是您经常做的事情,您可以做的是创建一个文件,使反射易于使用,然后使用 :load 命令将其加载到 REPL.

Assuming this is something you do often, what you could do is create a file that makes the reflection easy to use and then load it into the REPL using :load command.

这篇关于如何在 REPL 中使用具有默认(包)或私有访问级别的成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆