在 java 中,是否可以将 Serializable 接口添加到在运行时没有它的类? [英] In java, is it possible to add the Serializable interface to class that doesn't have it at runtime?

查看:37
本文介绍了在 java 中,是否可以将 Serializable 接口添加到在运行时没有它的类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想序列化一个类,它实现了 Serializable,但是它包含的一个对象没有实现 Serializable.

There is a class I want to serialize, and it implements Serializable, but one of the objects it contains does not implement Serializable.

有没有办法在运行时修改类以使其实现 Serializable 接口,以便我可以对其进行序列化?我无法在编译时更改它,因为它是第三方库.

Is there a way to modify the class at runtime to make it implement the Serializable interface so I can serialize it? I can't change it at compile time because its a third party library.

也许我必须使用某种字节码编写器或其他东西?

Maybe I would have to use some sort of bytecode writer or something?

包含类和包含类都在第 3 方库中,所以我认为我不能将某些内容标记为瞬态.包含类被标记为可序列化,但它包含的对象不是.

Both the containing class and contained class are in the 3rd party library so I don't think i can mark something as transient. The containing class is marked as serializable, but it contains an object that is not.

我可以为类编写自定义序列化方法,但不确定如何执行此操作,是否必须使用反射来获取私有变量的值?

I'm fine with writing a custom serialization method for the class, not sure how I would do this though, would I have to use reflection to get the values of the private variables?

推荐答案

阅读 Serializable 的 javadoc,我看到:

Reading the javadoc for Serializable, I see:

需要特殊处理的类在序列化和反序列化过程必须执行具有这些精确的特殊方法签名:

Classes that require special handling during the serialization and deserialization process must implement special methods with these exact signatures:

private void writeObject(java.io.ObjectOutputStream out)
     throws IOException
 private void readObject(java.io.ObjectInputStream in)
     throws IOException, ClassNotFoundException;
 private void readObjectNoData() 
     throws ObjectStreamException;

您可以使用它来手动序列化不合作的字段.您可以考虑使用 ASM,但似乎很难相信它是一个可维护的解决方案.

which you could use to manually serialize the uncooperative fields. You could look into using ASM, but it seems hard to believe that it is a maintainable solution.

这篇关于在 java 中,是否可以将 Serializable 接口添加到在运行时没有它的类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆