你如何从Java调用Scala对象? [英] How do you call Scala objects from Java?
问题描述
Java代码:
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代码:
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
class MyListener extends ActionListener {
override def actionPerformed(arg0: ActionEvent) {
println("Do something");
}
}
命令行:
scalac MyListener.scala
javac Main.java
java -cp /usr/share/java/scala-library.jar:. Main
推荐答案
我首先使用java.util。计时器 - 而不是javax.swing.Timer。除非您使用GUI运行应用程序,否则swing计时器将无法工作(即,如果您通过没有特殊命令行参数的控制台在Linux上运行它,它将无法工作 - 最好避免使用)。
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).
将此放在一边:
-
当您尝试运行代码时,请确保你在类路径中包含scala-library.jar。
Be sure, that when you try to run the code, you include scala-library.jar on your classpath.
不要忘记启动计时器 - timer.start()
Don't forget to start the timer - timer.start()
这段代码对我来说很好(Scala代码不需要修改):
This code worked fine for me (the Scala code required no modification):
MyListener myListener = new MyListener();
Timer timer = new Timer(1000, myListener);
timer.start();
Thread.sleep(10000);
这篇关于你如何从Java调用Scala对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!