Can we deny a java object from serialization other than giving transient keyword

一世执手 提交于 2019-11-29 07:57:54

问题


We can avoid serialising fields by using the transient keyword. Is there any other way of doing that?


回答1:


http://java.sun.com/javase/6/docs/platform/serialization/spec/security.html

SUMMARY:Preventing Serialization of Sensitive Data Fields containing sensitive data should not be serialized; doing so exposes their values to any party with access to the serialization stream. There are several methods for preventing a field from being serialized:

  1. Declare the field as private transient.
  2. Define the serialPersistentFields field of the class in question, and omit the field from the list of field descriptors.
  3. Write a class-specific serialization method (i.e., writeObject or writeExternal) which does not write the field to the serialization stream (i.e., by not calling ObjectOutputStream.defaultWriteObject).

Here are some links.

Declaring serialPersistenetFields.

Serialization architecture specification.

Security in Object Serialization.




回答2:


If for some reason transient doesn't suit, you can do the serialization directly by overriding the writeObject and readObject methods. Then you can include or omit any fields you need.




回答3:


This is what transient means as a a keyword. Its whole purpose is to stop the serialization of the data for whatever reason.

If you wanted a finer grain control over the process you can use the writeObject/readObject methods that the ObjectOutputStream/ObjectInputStream use as part of the serialization process, and you could combine that with some custom annotations or any logic you wanted.

private void readObject(java.io.ObjectInputStream stream)
 throws IOException, ClassNotFoundException;
private void writeObject(java.io.ObjectOutputStream stream)
 throws IOException



回答4:


You can create your own protocol with the Externalizable interface, that in my opinion is a nicer than Serializable since it doesn't contains private methods hooked by the JVM (writeObject and readObject). Instead of implementing the Serializable interface, you can implement Externalizable, which contains two methods:

public void writeExternal(ObjectOutput out) throws IOException;
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException

Unlike using Serializable nothing is provided for free now, though. That is, the protocol is entirely in your hands, overring transient/non triansient fields, etc.



来源:https://stackoverflow.com/questions/1292474/can-we-deny-a-java-object-from-serialization-other-than-giving-transient-keyword

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!