Is it possible to get serialVersionUID of java class at runtime

It is well known that runtime will generate a serialVersionUID field for your class if you were unable to explicitly define it.

But is it possible to get this value in runitme? Is it possible at runtime, having a link to .class , to get its serialVersionUID?

+4
source share
3 answers
 Integer i = new Integer(5);
 long serialVersionID = ObjectStreamClass.lookup(i.getClass()).getSerialVersionUID();

The above is an example code to get the serial version identifier of a class at runtime.

+11
source

. serialVersionUID - , , . , private protected, . , :

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

: [to] serialVersionUID... .

, . serialVersionUID , , "" " ". serialVersionUID - , , , .

And your proposed solution will not work. "Skipping instances of deserializing old versions of class [a] is not a solution. Serialization has already rejected it with the exception, if you serialVersionUIDsdon’t agree. Everything you do after that is already too late.

This seems like an XY issue. You want to make X, you think Y is the answer, so you ask about Y when you should ask about X. For the right solution, see Above.

+2
source

Source: https://habr.com/ru/post/1529975/


All Articles