简体   繁体   English

如何使扩展非序列化的Java类可序列化

[英]How to make a java class serializable that extends a non serializable

MyClass1 extends MyClass2 implements Serializable

I am trying to use saveOnInstanceState in my android app on a HashMap by using 我正在尝试通过使用HashMap上的android应用程序中使用saveOnInstanceState

 savedInstanceState.getSerializable()

I have does this with other hashmaps that that use custom classes but by making those classes Serializable however I seem to be getting errors with this even after I made this serializable because MyClass2 is not serializable. 我已经使用了其他使用自定义类的哈希表来做到这一点,但是通过将这些类设置为可序列化,但是即使我将其设置为可序列化之后,由于MyClass2不可序列化,我似乎还是会出现错误。 MyClass2 is a third party library and hence I cannot modify it and make it serializable, is there anything I can do? MyClass2是第三方库,因此我无法对其进行修改并使其可序列化,我可以做什么?

Thank you! 谢谢!

You cannot generally do this, as Jan's answer states. 正如Jan的回答所述,您通常无法执行此操作。 Under some circumstances there are work arounds that will make it happen, but they are a bit brittle even when they work. 在某些情况下,有一些解决方法可以使它实现,但是即使工作了,它们也会变得有些脆弱。 To have a chance at this, you'll need the following to apply: 为了有这个机会,您需要满足以下条件:

  • You have sufficient insight into the super class structure to know what data is necessary to capture its current state. 您对超级类结构有足够的了解,以了解捕获其当前状态所需的数据。
  • You need to have access (either through public or protected member variables or through something like getters) to the data necessary to capture its current state. 您需要(通过公共或受保护的成员变量或通过类似getter的方法)访问捕获其当前状态所需的数据。
  • You need to have access (either through public or protected member variables or through something like setters) to change the data fields necessary to reconstitute its current state. 您需要具有访问权限(通过公共或受保护的成员变量或通过setter之类的东西)来更改重构其当前状态所需的数据字段。
  • You need to use either the serialPersistentFields approach or a carefully constructed writeObject / readObject pair of implementations that save / read the data from the super class during serialization and deserialization. 您需要使用serialPersistentFields方法或精心构造的一对writeObject / readObject实现,以在序列化和反序列化期间保存/读取超类的数据。 This will necessarily require the knowledge of and access to the super class structure described in the earlier bullets. 这必然需要了解和访问前面的项目符号中描述的超类结构。
  • The super class must have a no-arg constructor. 超类必须具有无参数构造函数。 (This won't matter for serializing, but you'll need it when you de-serialize.) (这与序列化无关紧要,但是在反序列化时将需要它。)

Of course in doing all of this, you're going to use some knowledge of the super class, which means if the super class implementation changes, this may break in hard-to-find ways. 当然,在完成所有这些操作后,您将使用一些有关超类的知识,这意味着,如果超类的实现发生变化,则可能会以难以发现的方式中断。

Unfortunately you can't. 不幸的是你不能。 If you could do this, it would be a security flaw, as you could serialize every class, even if the class was not supposed to. 如果可以做到这一点,那将是一个安全漏洞,因为即使不应该对类进行序列化,您也可以对其进行序列化。

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

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