[英]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: 为了有这个机会,您需要满足以下条件:
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. 这必然需要了解和访问前面的项目符号中描述的超类结构。 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.