Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to serialize only a very few properties in a Java class

Recently in an interview I was asked a question:

There are 100 properties in a Java class and I should be able to serialize only 2 of the properties. How is this possible?

Marking all the 98 properties was not the answer as it is not efficient. My answer was to carve out those properties into a separate class and make it serializable.

But I was told that, I will not be allowed to modify the structure of the class. Well, I tried to find an answer in online forums, but in vain.

like image 801
Betta Avatar asked Jun 20 '15 12:06

Betta


2 Answers

The answer is transient keyword of java. if you make a property of a class transient it will not be serialized or deserialized. For example:

private transient String nonSerializeName;
like image 185
A.v Avatar answered Oct 06 '22 01:10

A.v


You could override the serialization behavior without using Externalizable interface,

you need to add following methods and do the needful there,

private void writeObject(ObjectOutputStream out) throws IOException;

private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException;

for example class could look like this,

class Foo{
  private int property1;
  private int property2;
  ....
  private int property100;

  private void writeObject(ObjectOutputStream out) throws IOException
  {
     out.writeInt(property67);
     out.writeInt(property76);
  }

  private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException
  {
    property67 = in.readInt();
    property76 = in.readInt();
  }
}

Refer this for more details

like image 24
Low Flying Pelican Avatar answered Oct 05 '22 23:10

Low Flying Pelican