ivstas
ivstas

Reputation: 1233

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?

Upvotes: 11

Views: 6319

Answers (4)

Jin Kwon
Jin Kwon

Reputation: 22027

Here comes a slightly modified version of the accepted answer regarding the nullability of the ObjectStreamClass#lookup method.

Optional.ofNullable(ObjectStreamClass.lookup(c))
        .map(ObjectStreamClass::getSerialVersionUID)
        .orElse(0L))

Upvotes: 0

user207421
user207421

Reputation: 311039

What I want: to force my code [to] change serialVersionUID automatically ... when I change internal structure of these classes.

No you don't. You want to keep the serialVersionUID the same forever, and to restrict the internal changes to what can be handled automatically by Serialization, for which you need to consult the Versioning chapter of the Object Serialization Specification. Changing the serialVersionUID on every class change is an urban myth which unfortunately has been far too widely propagated and accepted.

And your proposed solution won't work either. 'Skipping deserialization instances of old versions of [a] class' isn't a solution to anything. Serialization will already have rejected it with an exception if the serialVersionUIDs don't agree. Anything you do after that is already too late.

This is sounding like an XY problem. You want to do X, you think Y is the answer, so you ask about Y, when you should be asking about X. For the correct solution see above.

Upvotes: 2

AlexR
AlexR

Reputation: 115388

Sure you can. serialVersionUID is a regular static variable, so you can access it when you want. The only problem is that it is typically defined as private or protected, so you can access it from the class itself only. To access it from outside you can use reflection:

Class<?> clazz = obj.getClass();
Field f = clazz.getDeclraredField("serialVersionUID");
f.setAccessible(true);
long uid = (long)f.getValue();

Upvotes: 2

Sagar Gandhi
Sagar Gandhi

Reputation: 965

 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.

Upvotes: 26

Related Questions