使用Java的包对象中定义的Scala类 [英] Using Scala class defined in package object from Java
问题描述
以下Scala示例在包对象中定义了一个类:
The following Scala example defines a class inside a package object:
package com.mycompany
package object test {
class MyTest {
def foo(): Int = {
42
}
}
}
将生成以下三个类:
com/mycompany/test/package.class
com/mycompany/test/package$.class
com/mycompany/test/package$MyTest.class
尝试使用Java中的MyTest
类时出现问题.我认为,由于package$MyTest
的名称中包含$,Java不承认其存在.不过,package$
类是可访问的.
The problem arises when trying to use the MyTest
class from Java. I think that since package$MyTest
contains a $ in the name, Java is not acknowledging its existence. Nevertheless, the package$
class is accessible.
在package$MyTest.class
上运行javap
会返回:
Compiled from "Test.scala"
public class com.mycompany.test.package$MyTest {
public int foo();
public com.mycompany.test.package$MyTest();
}
我尝试使用Eclipse,Intellij和Netbeans访问该类,但没有成功. 是否可以使用Java包对象中定义的Scala类?
I've tried accessing the class using Eclipse, Intellij and Netbeans, without success. Is it possible to use Scala classes defined in package objects from Java?
推荐答案
在 package对象中定义类 test
当前的实现方式与在 package中定义它的方式不同 test
,尽管它可能应该这样做(它被跟踪为 SI-4344 ).
Defining a class inside the package object test
is currently not implemented the same way as defining it inside the package test
, although it probably should (this is being tracked as SI-4344).
因此,通常最好的做法是仅将不能顶级的定义(例如vals,defs等)放入包对象中(毕竟这是包对象的全部要点),并保留class/对象定义转换为普通的包装定义:
Because of that, it is usually good practice to place into the package object only definitions that cannot be top level, like vals, defs, etc. (this is the whole point of package objects after all), and leave class/object definitions into a normal package definition:
package com.mycompany
package object test {
// vals, defs, vars, etc.
val foobar = 42
}
package test {
// classes, objects, traits, etc.
class MyTest {
def foo(): Int = {
42
}
}
}
这将产生一个普通的MyTest
类,可以从Java轻松访问:
This will produce a normal MyTest
class, easily accessible from Java:
com/mycompany/test/MyTest.class
com/mycompany/test/package.class
com/mycompany/test/package$.class
这篇关于使用Java的包对象中定义的Scala类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!