How to add a SerialVersionUID to a Class[_] instance in Scala?

有些话、适合烂在心里 提交于 2019-12-23 13:23:05

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!