aspose file tools
The moose likes Java in General and the fly likes Object serialization Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Java » Java in General
Reply Bookmark "Object serialization" Watch "Object serialization" New topic
Author

Object serialization

Allan Wang
Greenhorn

Joined: Apr 23, 2001
Posts: 20
java fans:
If I extend a class which cann't be modified and didn't implements seriable. When I serialize my object, it didn't serialize the member variable inherited from parent class. Are there methods to serialize the object including the parent class without modifying the parent class?
Any help will be appreciated.
Please see the foll. snippet.
===============================================
import java.io.*;
class AA{
int x=11;
public void setx(int a){x=a;}
}

class BB extends AA implements Serializable{
int y=22;
public void sety(int a){y=a;}
}

public class test{
public static void main(String args[]) {
BB b=new BB();
b.setx(33);
b.sety(44);
try{
FileOutputStream fos=new FileOutputStream("xxx.yyy");
ObjectOutputStream oos=new ObjectOutputStream(fos);
System.out.println("befor: "+b.x+" and "+b.y);//33,44
oos.writeObject(b);
oos.close();
fos.close();
}catch (IOException e){
System.out.println("error write obj");
}
try{
FileInputStream fis=new FileInputStream("xxx.yyy");
ObjectInputStream ois=new ObjectInputStream(fis);
BB sb=(BB)(ois.readObject());
System.out.println("after: "+sb.x+" and "+sb.y);//11,44
ois.close();
fis.close();
}catch (IOException e){
System.out.println("error read obj");
}catch(ClassNotFoundException e){
}
}
}
Anonymous
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
It may not be very OO, but you could always add the same variable to your subclass and then do something like

in your constructor. That would place the x variable and its value in the Serializable class.
Dave Turner
Ranch Hand

Joined: Mar 13, 2001
Posts: 60
from the Java 1.3 API, java.io.serialization
Classes that require special handling during the serialization and deserialization process must implement special methods with these exact signatures:


So you can write your own object serialization methods for your class BB to control the serialization of the variable x in your non-serializable class AA.
You will need to use writeObject to output the values of x and y in Integer objects, and readObject to read them in again.
the following changes to your class BB should make the serialization work how you want it to.

HTH
Dave
Allan Wang
Greenhorn

Joined: Apr 23, 2001
Posts: 20
Thanks, Dave. Your answer is very helpful.
 
I agree. Here's the link: http://zeroturnaround.com/jrebel - it saves me about five hours per week
 
subject: Object serialization
 
Similar Threads
why no any exception
De-Serialization is returning Null values
Store a linked list into a file
serialization
compiler error saying method of serializable to be overridden