我可以使用scala类来实现Java的Java接口吗? [英] Can I use a scala class which implements a java interface from Java?
问题描述
我正在学习Scala并且好奇是否有可能:
I'm learning Scala and was curious if it would be possible to:
- 创建一个在Scala中实现Java接口的对象
- 将对象编译成类文件并将其jar起来
- 使用Java中的对象
我想在scala中实现一个自定义lucene查询解析器,并且能够让其他人从java应用程序访问它。
I want to implement a custom lucene query parser in scala and be able to let others access it from a java application.
推荐答案
我假设对象你实际上是指阶级。无论如何,答案是肯定的,你可以这样做。如果您希望在同一个项目中使用Scala / Java联合编译器,则需要利用它。例如:
I'm assuming that by "object" you actually mean "class". In any case, the answer is yes, you can do this. You will need to take advantage of the Scala/Java joint compiler if you want this all in the same project. For example:
public interface Parser {
public TokenIterator parse(InputStream is);
}
然后在Scala中:
class ParserImpl extends Parser {
def parse(is: InputStream) = ...
}
最后,再次使用Java:
Finally, in Java again:
public class Consumer {
public static void main(String[] args) {
Parser p = new ParserImpl(); // just like a Java class!
...
}
}
如果所有这些源文件在同一个项目中,然后您将需要使用以下命令调用来编译它们:
If all of these source files are in the same project, then you will want to compile them using the following invocation of commands:
$ scalac *.scala *.java
$ javac -classpath . *.java
第一个命令调用Scala / Java联合编译器,它将编译Scala源代码和只需足够的Java源来满足任何依赖关系。第二个命令使用类路径上最近编译的Scala类调用Java编译器。
The first command invokes the Scala/Java joint compiler, which will compile the Scala sources and just enough of the Java sources to satisfy any dependencies. The second command invokes the Java compiler with the recently-compiled Scala classes on the classpath.
这篇关于我可以使用scala类来实现Java的Java接口吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!