它像Scala那样将相伴物体的方法编纂成静态方法,使得从java法典中援引这些方法稍加容易。 例如,你可以撰写CompanionObject.method(而不是CompanionObject$)。 教育部 然而,有时似乎不相干的法典变化将打破这一行为。 我举这个例子来说明问题。
$ cat TestCompanion.scala
class TestCompanion
object TestCompanion {
def init2 {}
}
@SerialVersionUID(1L)
class TestCompanion2
object TestCompanion2 {
def init2 {}
}
$ scalac -version
Scala compiler version 2.9.0.1 -- Copyright 2002-2011, LAMP/EPFL
$ scalac TestCompanion.scala
$ javap TestCompanion
Compiled from "TestCompanion.scala"
public class TestCompanion extends java.lang.Object implements scala.ScalaObject{
public static final void init2();
public TestCompanion();
}
$ javap TestCompanion2
Compiled from "TestCompanion.scala"
public class TestCompanion2 extends java.lang.Object implements scala.ScalaObject{
public static final long serialVersionUID;
public static {};
public TestCompanion2();
}
So the only difference between TestCompanion and TestCompanion2 is that the latter is annotated with @SerialVersionUID, and init2 is compiled into a static method in TestCompanion but not in TestCompanion2.
谁能解释为什么这些班级的加油处理方式不同? 我看不出“SerialVersionUID”说明如何影响静态方法的提供。