简体   繁体   English

是否可以在运行时获取Java类的serialVersionUID

[英]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. 众所周知,如果您未能明确定义它,则运行时将为您的类生成serialVersionUID字段。

But is it possible to get this value in runitme? 但是有可能在runitme中获得此值吗? Is it possible in runtime, having reference to .class , obtain it's serialVersionUID ? 在运行时是否可以参考.class来 获取serial_VersionUID

 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. 上面是在运行时获取类的串行版本ID的示例代码。

What I want: to force my code [to] change serialVersionUID automatically ... when I change internal structure of these classes. 我想要的是:强制我的代码[自动]更改这些类的内部结构时自动更改serialVersionUID

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. 您希望永远保持serialVersionUID不变,并将内部更改限制为可以由序列化自动处理的内容,对此您需要查阅“对象序列化规范”的“版本控制”一章。 Changing the serialVersionUID on every class change is an urban myth which unfortunately has been far too widely propagated and accepted. 每次更改类时更改serialVersionUID都是一个城市神话,不幸的是,这一神话已被广泛传播和接受。

And your proposed solution won't work either. 而且您提出的解决方案也不起作用。 'Skipping deserialization instances of old versions of [a] class' isn't a solution to anything. “跳过旧版本的[a]类的反序列化实例”对任何事情都不是解决方案。 Serialization will already have rejected it with an exception if the serialVersionUIDs don't agree. 如果serialVersionUIDs不一致,则序列化将已拒绝它,但有一个例外。 Anything you do after that is already too late. 此后您做的任何事情都为时已晚。

This is sounding like an XY problem. 这听起来像是XY问题。 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. 您想做X,您认为Y是答案,所以当您应该询问X时,您询问Y。有关正确的解决方案,请参见上文。

Sure you can. 你当然可以。 serialVersionUID is a regular static variable, so you can access it when you want. serialVersionUID是常规静态变量,因此您可以在需要时访问它。 The only problem is that it is typically defined as private or protected , so you can access it from the class itself only. 唯一的问题是,它通常定义为privateprotected ,因此您只能从类本身访问它。 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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM