1

I am new to serialization concept and i am trying to serialize PointF class as i need to send it over socket connection (I am using ObjectOutputStream and ObjectInputStream). My problem is while sending no matter what values i have in my PointF object while sending , after receiving i get default value.

example if i sent pointF(1.0,4.0) i get (0.0,0.0).

Following is my code for implimenting serializable.

public class MyPointF extends PointF implements Serializable {

/**
 * 
 */
private static final long serialVersionUID = -455530706921004893L;

public MyPointF() {
    super();
}

public MyPointF(float x, float y) {
    super(x, y);
}
}

Can anybody point out the problem? Also, after searching a little i found that this thing happens to android.canvas.Path class also. Please correct me where I am Wrong.

Ana
  • 841
  • 10
  • 28

2 Answers2

2

Your superclass PointF is not serialisable. That means that the following applies:

To allow subtypes of non-serializable classes to be serialized, the subtype may assume responsibility for saving and restoring the state of the supertype's public, protected, and (if accessible) package fields. The subtype may assume this responsibility only if the class it extends has an accessible no-arg constructor to initialize the class's state. It is an error to declare a class Serializable if this is not the case. The error will be detected at runtime.

During deserialization, the fields of non-serializable classes will be initialized using the public or protected no-arg constructor of the class. A no-arg constructor must be accessible to the subclass that is serializable. The fields of serializable subclasses will be restored from the stream.

See: http://docs.oracle.com/javase/7/docs/api/java/io/Serializable.html

You will need to look at readObject and writeObject:

Classes that require special handling during the serialization and deserialization process must implement special methods with these exact signatures:

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

See also here: Java Serialization with non serializable parts for more tips and tricks.

Community
  • 1
  • 1
Greg Kopff
  • 15,945
  • 12
  • 55
  • 78
0

I finally found the solution. Thanx @Greg and the other comment that has now been deleted. The solution is that instead of extending these objects we can make stub objects. As i was calling super from constructor the x and y fields were inherited from base class that is not serializable. so they were not serialized and there values were not sent.

so i mofidfied my class as per your suggestions

public class MyPointF implements Serializable {

/**
 * 
 */
private static final long serialVersionUID = -455530706921004893L;

public float x;
public float y;

public MyPointF(float x, float y) {
    this.x = x;
    this.y = y;
}
}
Ana
  • 841
  • 10
  • 28