如何在 Scala REPL 中重新加载类或包? [英] How to reload a class or package in Scala REPL?

查看:48
本文介绍了如何在 Scala REPL 中重新加载类或包?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我几乎总是打开一两个 Scala REPL 会话,这使得对 Java 或 Scala 类进行快速测试变得非常容易.但是如果我更改一个类并重新编译它,REPL 会继续加载旧的.有没有办法让它重新加载类,而不必重新启动 REPL?

I almost always have a Scala REPL session or two open, which makes it very easy to give Java or Scala classes a quick test. But if I change a class and recompile it, the REPL continues with the old one loaded. Is there a way to get it to reload the class, rather than having to restart the REPL?

举一个具体的例子,假设我们有文件 Test.scala:

Just to give a concrete example, suppose we have the file Test.scala:

object Test { def hello = "Hello World" }

我们编译它并启动 REPL:

We compile it and start the REPL:

~/pkg/scala-2.8.0.Beta1-prerelease$ bin/scala
Welcome to Scala version 2.8.0.Beta1-prerelease
(Java HotSpot(TM) Server VM, Java 1.6.0_16).
Type in expressions to have them evaluated.
Type :help for more information.

scala> Test.hello
res0: java.lang.String = Hello World

然后我们将源文件改为

object Test {
  def hello = "Hello World"
  def goodbye = "Goodbye, Cruel World"
}

但我们不能使用它:

scala> Test.goodbye
<console>:5: error: value goodbye is not a member of object Test
       Test.goodbye
            ^

scala> import Test;
<console>:1: error: '.' expected but ';' found.
       import Test;

推荐答案

类重新加载不是一个容易的问题.事实上,这是 JVM 非常困难的事情.不过,您确实有几个选择:

Class reloading is not an easy problem. In fact, it's something that the JVM makes very difficult. You do have a couple options though:

  • 在调试模式下启动 Scala REPL.JVM 调试器具有一些在方法级别工作的内置重新加载.它不会帮助您处理您提供的案例,但它会处理一些简单的事情,例如更改方法实现.
  • 使用 JRebel(http://www.zeroturnaround.com/jrebel).JRebel 基本上是一个超级充电的类重新加载解决方案虚拟机.它可以处理成员添加/删除、新的/删除的类、定义更改等.它不能处理的唯一一件事是类层次结构的更改(添加一个超级接口,用于例子).它不是免费工具,但它们确实提供了仅限于 Scala 编译单元的补充许可.
  • Start the Scala REPL in debug mode. The JVM debugger has some built-in reloading which works on the method level. It won't help you with the case you gave, but it would handle something simple like changing a method implementation.
  • Use JRebel (http://www.zeroturnaround.com/jrebel). JRebel is basically a super-charged class reloading solution for the JVM. It can handle member addition/removal, new/removed classes, definition changes, etc. Just about the only thing it can't handle is changes in class hierarchy (adding a super-interface, for example). It's not a free tool, but they do offer a complementary license which is limited to Scala compilation units.

不幸的是,这两者都受到 Scala REPL 实现细节的限制.我使用 JRebel,它通常可以解决问题,但仍然存在 REPL 不会反映重新加载的类的情况.不过,总比没有好.

Unfortunately, both of these are limited by the Scala REPL's implementation details. I use JRebel, and it usually does the trick, but there are still cases where the REPL will not reflect the reloaded class(es). Still, it's better than nothing.

这篇关于如何在 Scala REPL 中重新加载类或包?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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