我在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));
那么,我如何从Java引用PressureSensor
案例对象?我反编译了PressureSensor
和PressureSensor$
类的字节代码,产生了以下内容:
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();
}
但这并没有产生任何好的见解。
答案 0 :(得分:36)
说:
my.awesome.package.PressureSensor$.MODULE$
答案 1 :(得分:11)
PressureSensor$.MODULE$
应该为您提供案例对象的实例。
答案 2 :(得分:6)
这仍然是一个黑客,但在我看来,在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));