Friday, 12 August 2011

Marker Interface

About Serializable Marker interface:


A class implements this interface to indicate that its non-transient data members can be written to an ObjectOutputStream. The ObjectOutputStream private method writeObject() contains a series of instanceof tests to determine writeability, one of which looks for the Serializable interface. If any of these tests fails, the method throws a NotSerializableException.


  1. When should i implment Serializble interface?
  2. Why do we do that?
  3. Does it give any advantages or security?
1)  Answer 1
It lets you take an object or group of objects, put them on a disk or send them through a wire or wireless transport mechanism, then later, perhaps on another computer, reverse the process: resurrect the original object(s). The basic mechanisms are to flatten object(s) into a one-dimensional stream of bits, and to turn that stream of bits back into the original object(s).
Like the Transporter on Star Trek, it's all about taking something complicated and turning it into a flat sequence of 1s and 0s, then taking that sequence of 1s and 0s (possibly at another place, possibly at another time) and reconstructing the original complicated "something."
       So, implement the Serializable interface when you need to store a copy of the object, send them it to another process on the same system or over the network.
       Answer 2:
       Implement the Serializable interface when you want to be able to convert an instance of a class into a series of bytes or when you think that a Serializable object might reference an instance of your class.

2) Answer 1:
      Because you want to store or send an object.
    Answer 2:
     Serializable classes are useful when you want to persist instances of them or send them over a wire

3) It makes storing and sending objects easy. It has nothing to do with security.
Instances of Serializable classes can be easily transmitted. Serialization does have some security consequences, however. Read Joshua Bloch's "Effective Java".






Serialization is fraught with pitfalls. Automatic serialization support of this form makes the class internals part of the public API (which is why javadoc gives you the persisted forms of classes).
For long-term persistence, the class must be able to decode this form, which restricts the changes you can make to class design. This breaks encapsulation.
Serialization can also lead to security problems. By being able to serialize any object it has a reference to, a class can access data it would not normally be able to (by parsing the resultant byte data).
There are other issues, such as the serialized form of inner classes not being well defined.
Making all classes serializable would exacerbate these problems. Check out Effective Java Second Edition, in particular Item 74: Implement Serializable judiciously.


No comments:

Post a Comment