Vinoth Kumar C M
Vinoth Kumar C M

Reputation: 10588

Programmatically Adding SerialVersion Ids for Java files

We have hundreds of java Entities which are reverse engineered through Hibernate tools. The Entity classes seem to implement java.io.Serializable interface, but doesn't have serialVersionUID.

We are tasked with adding serialVersionUID to these files (worst case, we'll have to do it manually). Is there some other way we can do it ? An ideal solution will be to do it in the reverse engineering step itself, but it's also okay to pass in the package name and add serialVersionUID to the Entity classes.

We are using Hibernate 3.0

Upvotes: 0

Views: 231

Answers (1)

liorsolomon
liorsolomon

Reputation: 1873

I started writing my own code to implement this, but then I found a much simpler solution. The following bash script runs recursively through your *.java files (run it from the root of your project) and searches all the files implementing Serializable.

#!/bin/bash  

files=$(find . -name '*.java' | xargs grep -i -l "Serializable"  | xargs grep "interface" -L | xargs grep "serialVersionUID" -L)

then it will print the serialuid it added and to which class

do
 serial=$(jot -r 1 1000000000000 9999999999999)
 echo "Adding serialVersionUID $serial to $f"

then it will search for the string "implements Serializable" and add under that line the serialVersionUID variable

sed -i '' "/implements Serializable/ a\
    private static final long serialVersionUID =${serial}L;
" $f

done

Here is the original post

Upvotes: 2

Related Questions