你如何从 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 01:33:00  来源:igfitidea点击:

How do you call Scala objects from Java?

javascala

提问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:

把它放在一边:

  1. Be sure, that when you try to run the code, you include scala-library.jar on your classpath.

  2. Don't forget to start the timer - timer.start()

  1. 请确保,当您尝试运行代码时,您将 scala-library.jar 包含在您的类路径中。

  2. 不要忘记启动计时器 - 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);