SJunejo
SJunejo

Reputation: 1336

Generate SerialVersionUID for Java Class

From heading it is expected to be the same old question but trust me this is different.

I am working with an EJB3 and off course if I have to invoke it remotely I have to make all my data object implement Serializable interface.

The problem is that most my data objects are generated (using Velocity Templates), compiled and package in one go. For now I hard coded the default serialVersionUID in every class as follows;

private static final long serialVersionUID = 1L;

But I am wondering if there is any way I can do following;

private static final long serialVersionUID = getSerialUID();
private static long getSerialUID() {
    // Serial Version Algo code here
}

Also, is there any problem in using Default serialVersionUID? Do I really need to generate a unique ID using Algo?

Upvotes: 0

Views: 6422

Answers (2)

SJunejo
SJunejo

Reputation: 1336

First answer is helpful but it does not tell you how to generate class serialVersionUID. I have done it as follows as all of my classes are generated by Velocity Template I have to get it at the time of code generation. So I created a method to get hashcode() for all the properties and add them in the end to get the serialVersionUID. For example;

public int getSerialVerionUID() {
    return getName().hashCode() + 
        getTypeName().hashCode() +
        getCardinality().hashCode() +
        getComplexity().hashCode();
}

So as soon as any of the property changes, we will have the different UID and that's all we are looking for.

Hope this helps to some one.

Upvotes: 1

Viral Patel
Viral Patel

Reputation: 8601

  1. Is there any problem in using Default serialVersionUID?

    There is no issue in using default serialVersionUID unless you have more than one versions of same class.

    Read: What is a serialVersionUID and why should I use it?

  2. Do I really need to generate a unique ID using Algo?

    Answer would be again no. You dont have to generate a unique ID using any Algo. If you have different versions of same class then you can provide a unique number as serialVersionUID (e.g. serialVersionUID=123 and serialVersionUID=456)

I strongly recommend you to go through Javadoc java.io.Serializable

Upvotes: 1

Related Questions