Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to get serialVersionUID of the java class in runtime

It's well known that runtime will genereate serialVersionUID field for your class, if you failed to explicitly define it.

But is it possible to get this value in runitme? Is it possible in runtime, having reference to .class, obtain it's serialVersionUID?

like image 387
ivstas Avatar asked Mar 04 '14 10:03

ivstas


People also ask

How does serialVersionUID work in Java?

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.

Can two classes have same serialVersionUID?

Technically you can't prevent two classes from having the same serial version UID, much like you can't prevent two objects from having the same system hash code.

What is serialVersionUID in Java exception?

The serialization at runtime associates with each serializable class a version number called a serialVersionUID, which is used during deserialization to verify that the sender and receiver of a serialized object have loaded classes for that object that are compatible with respect to serialization.


1 Answers

 Integer i = new Integer(5);
 long serialVersionID = ObjectStreamClass.lookup(i.getClass()).getSerialVersionUID();

Above is the sample code to get serial version id of the class at runtime.

like image 121
Sagar Gandhi Avatar answered Oct 20 '22 20:10

Sagar Gandhi