你如何从 Java 调用 Scala 对象?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1179406/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do you call Scala objects from Java?
提问by givanse
Java code:
爪哇代码:
import javax.swing.Timer;
class Main {
public static void main(String args[]) {
MyListener myListener = new MyListener();
Timer timer = new Timer(1000, myListener);
timer.start();
while(timer.isRunning()) {
System.out.print(".");
}
}
}
Scala code:
斯卡拉代码:
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
class MyListener extends ActionListener {
override def actionPerformed(arg0: ActionEvent) {
println("Do something");
}
}
Command line:
命令行:
scalac MyListener.scala
javac Main.java
java -cp /usr/share/java/scala-library.jar:. Main
采纳答案by sanity
I'd start by using java.util.Timer - not javax.swing.Timer. The swing timer won't work unless you are running your app with a GUI (ie. it won't work if you run it on Linux through a console without a special command line parameter - best avoided).
我首先使用 java.util.Timer - 而不是 javax.swing.Timer。除非您使用 GUI 运行您的应用程序,否则摆动计时器将无法工作(即,如果您通过没有特殊命令行参数的控制台在 Linux 上运行它,它将无法工作 - 最好避免)。
Setting that aside:
把它放在一边:
Be sure, that when you try to run the code, you include scala-library.jar on your classpath.
Don't forget to start the timer - timer.start()
请确保,当您尝试运行代码时,您将 scala-library.jar 包含在您的类路径中。
不要忘记启动计时器 - timer.start()
This code worked fine for me (the Scala code required no modification):
这段代码对我来说很好(Scala 代码不需要修改):
MyListener myListener = new MyListener();
Timer timer = new Timer(1000, myListener);
timer.start();
Thread.sleep(10000);

