Help with Serializable
stevieweasle_at_yahoo.co.uk
Date: 11/30/03
- Next message: Michel Taillefer: "Re: Help needed for Robohelp"
- Previous message: Ike: "Re: Future of Java"
- Next in thread: Sudsy: "Re: Help with Serializable"
- Reply: Sudsy: "Re: Help with Serializable"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: 29 Nov 2003 17:53:07 -0800
Hi
I can't work out why my writeObject and readObject methods are not
working with the Serializable interface. I want to be able to write
private fields to my output stream without using get and set methods.
I've tried with and without defaultWriteObject and defaultReadObject
methods, and also with and without the transient keyword. "testString"
does not get written to the xml file and I don't think either
writeObject or readObject are getting called during Serialization. No
errors are generated and if I add getTestString and setTestString
methods for testString then it starts working.
Here is the code, I'm using J2SE 1.4.2.
I'd really appeciate any help.
Thanks
TestSerialization.Java
----------------------
package Test;
import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class TestSerialization {
public static void saveObject() {
Test test = new Test();
test.setTest("Test to use writeObject and readObject");
FileOutputStream fos = null;
try {
fos = new FileOutputStream("test.xml");
XMLEncoder oos = new XMLEncoder(fos);
oos.writeObject(test);
oos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void readObject() {
try {
FileInputStream fis = new FileInputStream("test.xml");
XMLDecoder ois = new XMLDecoder(fis);
Test test = (Test) ois.readObject();
ois.close();
System.out.print(test);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
saveObject();
readObject();
}
}
Test.java
---------
package Test;
import java.io.Serializable;
import java.io.IOException;
public class Test implements Serializable {
private transient String testString;
public Test() {
testString = "";
}
public void setTest(String testString) {
this.testString = testString;
}
private void writeObject(java.io.ObjectOutputStream out) throws
IOException {
out.defaultWriteObject();
out.writeObject(testString);
}
private void readObject(java.io.ObjectInputStream in) throws
IOException, ClassNotFoundException {
in.defaultReadObject();
this.testString = (String) in.readObject();
}
public String toString() {
return testString;
}
}
- Next message: Michel Taillefer: "Re: Help needed for Robohelp"
- Previous message: Ike: "Re: Future of Java"
- Next in thread: Sudsy: "Re: Help with Serializable"
- Reply: Sudsy: "Re: Help with Serializable"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]