问题
I need to create an instances an instance of java.lang.Class
that is otherwise identical to classOf[MyClass]
but also has a SerialVersionUID
, which MyClass
does not have. MyClass
is a Scala-2.10 class. One problem is that in Java SerialVersionUID
is a static final
while in Scala SerialVersionUID
since Scala does not have statics.
If MyClass
was a Java class I think I would be able do this using Javassist:
val ctclass = javassist.ClassPool.getDefault().get("mypackagage.MyClass")
val field = javassist.CtField.make(
"private static final long serialVersionUID = 1L;",
ctclass)
ctclass.addField(field)
val cls = ctclass.toClass()
However, this does not quiet work for Scala classes. I tried to use this in a ClassLoader for de-serialization.
there were no compile or run time errors during deserialization, but the deserialized object is incomplete, so there must be some more subtle problem. The gory details are described here. Presumably the problem comes from how static final
fields are dealt with in Scala and the fact that Javassist only understands
Java. How can I do it so it is 100% correct for Scala classes using either Javassist or any other means.
回答1:
If I compile the following class:
@SerialVersionUID(1L)
object MyClass {
}
$ scalac MyCLass.scala
$ javap -cp MyClass$
Compiled from "MyClass.scala"
public final class MyClass$ {
public static final MyClass$ MODULE$;
public static final long serialVersionUID;
public static {};
}
I'm not familiar with javaassist, but this shows where you need to put the additional field, FWIW.
来源:https://stackoverflow.com/questions/17385725/how-to-add-a-serialversionuid-to-a-class-instance-in-scala