Scala:Trait Companion对象在Java中不可见 [英] Scala: Trait Companion Object is not visible in Java
问题描述
Scala 中的特征的伴随对象在Scala中没有可见性问题 :
trait ProtocolPacket extends Serializable {
def toByteArray: Array[Byte]
}
object ProtocolPacket {
def getStreamType( streamBytes: Array[Byte] ) = {
// ...
}
}
但是在Java方面(例如在jar中获取上述内容), ProtocolPacket.getStreamType
不可见。实际上,(由IDEA反编译)源没有为 ProtocolPacket
However on Java side (e.g. gets the above in a jar), a ProtocolPacket.getStreamType
is not visible. In fact a (decompiled by IDEA) source does not have a getStreamType
method defined for a ProtocolPacket
我在SO上找到类似的点击 Companion $ MODULE $
,但被IDEA欺骗:)如下所示:
I found similar hits on SO regarding Companion$MODULE$
, but was tricked by IDEA :) as shown below:
以上编译并运行正常(shell和/或IDEA本身),以防其他人被困。
The above compiles and runs fine (shell and/or IDEA itself), in case anybody else gets trapped.
推荐答案
查看 javap
输出,您会发现:
$ javap ProtocolPacket
public interface ProtocolPacket extends scala.Serializable{
public abstract byte[] toByteArray();
}
和同伴对象:
$ javap ProtocolPacket$
public final class ProtocolPacket$ extends java.lang.Object implements scala.ScalaObject,scala.Serializable{
public static final ProtocolPacket$ MODULE$;
public static {};
public void getStreamType(byte[]);
public java.lang.Object readResolve();
}
这让我相信你可以写的Java:
this makes me believe in Java you can write:
ProtocolPacket$.MODULE$.getStreamType(/**/)
这篇关于Scala:Trait Companion对象在Java中不可见的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!