34

我在 Scala 中创建了一个案例对象的层次结构,如下所示:

package my.awesome.package

sealed abstract class PresetShapeType(val displayName: String)

case object AccelerationSensor extends PresetShapeType("Acceleration Sensor")
case object DisplacementSensor extends PresetShapeType("Displacement Sensor")
case object ForceSensor        extends PresetShapeType("Force Sensor")
case object PressureSensor     extends PresetShapeType("Pressure Sensor")
case object StrainSensor       extends PresetShapeType("Strain Sensor")

我也有一段我想访问的 Java 代码PressureSensor,但以下代码不起作用:

package my.awesome.package.subpackage;

import my.awesome.package.PressureSensor;

// Do some stuff, then...

DVShape newshape = DVShapeFactory.createPresetShape(PressureSensor, new Point3f(0,0,0));

那么,如何PressureSensor从 Java 中引用 case 对象呢?我反编译了PressureSensorPressureSensor$类的字节码,结果如下:

Compiled from "DVShapeFactory.scala"
public final class org.nees.rpi.vis.PressureSensor extends java.lang.Object{
    public static final java.lang.Object productElement(int);
    public static final int productArity();
    public static final java.lang.String productPrefix();
    public static final int $tag();
    public static final java.lang.String displayName();
}

Compiled from "DVShapeFactory.scala"
public final class org.nees.rpi.vis.PressureSensor$ extends org.nees.rpi.vis.PresetShapeType implements scala.ScalaObject,scala.Product,java.io.Serializable{
    public static final org.nees.rpi.vis.PressureSensor$ MODULE$;
    public static {};
    public org.nees.rpi.vis.PressureSensor$();
    public java.lang.Object readResolve();
    public java.lang.Object productElement(int);
    public int productArity();
    public java.lang.String productPrefix();
    public final java.lang.String toString();
    public int $tag();
}

但这并没有产生任何深刻的见解。

4

3 回答 3

38

来自Java,说:

my.awesome.package.PressureSensor$.MODULE$
于 2010-04-01T15:16:47.793 回答
11

PressureSensor$.MODULE$应该给你case对象的实例。

于 2010-04-01T15:18:19.627 回答
7

这仍然是一个 hack,但我认为在 Java 中更具可读性。只需添加一个方法来显式返回对单例实例的引用(它在类上显示为静态方法):

sealed abstract class PresetShapeType(val displayName: String)

case object AccelerationSensor extends PresetShapeType("Acceleration Sensor") { def instance = this }
case object DisplacementSensor extends PresetShapeType("Displacement Sensor") { def instance = this }
case object ForceSensor extends PresetShapeType("Force Sensor") { def instance = this }
case object PressureSensor extends PresetShapeType("Pressure Sensor") { def instance = this }
case object StrainSensor extends PresetShapeType("Strain Sensor") { def instance = this }

然后在Java中:

import my.awesome.package.PressureSensor;
DVShape newshape = DVShapeFactory.createPresetShape(PressureSensor.instance(), new Point3f(0,0,0));
于 2013-04-16T15:40:49.390 回答