think in java - IO - object serialization

1641 ワード

# why we need object serialization?
- There are situations in which it would be incredibly useful if an object could exist and hold its information even when the program isn't running.
- We can get similar effect by writing the information to a file or to a DB.
- in the spirit of making everything an object, it would be quite convenient to declare an object to be "persistent"
# what is object serialization?
which allows you to take any object that implements Serializable interface and turn it into a sequence of bytes that can be later fully restored to regenerate the original object.
Object serialization was added to java to support 2 features: RMI && JavaBean.
# Seriablable vs Externalizable
by implementating  java.io.Serializable , you get "automatic"serialization capability for objects of your class. No need to implement any other logic, it'll just work. The Java runtime will use reflection to figure out how to marshal and unmarshal your objects.
In earlier version of Java, reflection was very slow, and so serializaing large object graphs (e.g. in client-server RMI applications) was a bit of a performance problem. To handle this situation, the  java.io.Externalizable  interface was provided, which is like  java.io.Serializable  but with custom-written mechanisms to perform the marshalling and unmarshalling functions (you need to implement  readExternal  and  writeExternal  methods on your class). This gives you the means to get around the reflection performance bottleneck.