Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add @SerialVersionUID to an anonymous class?

I want to translate the following piece of code from Java to Scala:

Foo foo = new Foo() { private static final long serialVersionUID = 12345L; }

Class Foo is an abstract class.

How does the equivalent code look like in Scala?

like image 574
soc Avatar asked Apr 05 '11 10:04

soc


People also ask

How do I assign a serialVersionUID?

File -> Settings -> Editor -> Inspections -> Java -> Serialization issues : Find serialization class without serialVersionUID and check it. Back to the editor, clicks on the class name, ALT + ENTER (Windows), it will prompts the Add serialVersionUID field option. A new serialVersionUID is auto-generated.

What is serialVersionUID what would happen if you don't define this?

SerialVersionUID is a unique identifier for each class, JVM uses it to compare the versions of the class ensuring that the same class was used during Serialization is loaded during Deserialization. Specifying one gives more control, though JVM does generate one if you don't specify.

What will happen if I will not declare serialVersionUID in a class which implements Serializable?

If serialVersionUID is not provided in a Serializable class, the JVM will generate one automatically. However, it is good practice to provide the serialVersionUID value and update it after changes to the class so that we can have control over the serialization/deserialization process.

When can you use anonymous classes?

Anonymous classes enable you to make your code more concise. They enable you to declare and instantiate a class at the same time. They are like local classes except that they do not have a name. Use them if you need to use a local class only once.


1 Answers

There is a Scala annotation for adding the ID. But it seems, that you cannot apply this solution to anonymous inner classes. However, according to the Scala FAQ:

In Scala private values that evaluate to a constant known at compile-time are turned into private static final Java variables. This undocumented feature should do the trick for you. Just check out the implementation of lists in Scala (see e.g. src/scala/List.java). Both classes :: and Nil have a field serialVersionUID of the following form: private val serialVersionUID = numeric literal;

The code

object Ser extends Application {
    trait Foo { def xy: Int }
    val x = new Foo with java.io.Serializable { def xy = 2; private val serialVersionUID = 1L }
}

compiles fine with the 2.8.1 compiler. I haven't tested it, though as to whether the serial version of the resulting class is actually the one supplied.

like image 117
Dirk Avatar answered Oct 24 '22 21:10

Dirk