如何把对象序列化:
Serializable接口可以实现对象的序列化,其目的是,将程序中的一个对象存储或通过网路传输,然后在另一个程序中还原出一个和原有对象一致的对象。
可以通过指定关键transient使对象中的某个数据元素不被还原,这种方式常用于安全上的保护。比如对象中保存的密码。
应注意的是被序列化的CLASS应该能在还原处的classpath中找到类的定义。
Serializable接口可以实现对象的序列化,其目的是,将程序中的一个对象存储或通过网路传输,然后在另一个程序中还原出一个和原有对象一致的对象。
可以通过指定关键transient使对象中的某个数据元素不被还原,这种方式常用于安全上的保护。比如对象中保存的密码。
应注意的是被序列化的CLASS应该能在还原处的classpath中找到类的定义。
import
java.io.
*
;
class Data implements Serializable { // Data class is aslo declare as
// Serializable
public int data;
public Data() {
data = ( int ) (Math.random() * 100 );
}
}
class TestObj implements Serializable {
transient private int testInt; // testInt is declare as a transient element
private String testString;
private Data testData;
TestObj( int testInt, String testString) {
this .testInt = testInt;
this .testString = testString;
testData = new Data();
}
public String toString() {
String s;
s = Integer.toString(testInt) + " " + testString + " "
+ Integer.toString(testData.data);
return s;
}
}
public class WriteObject {
public static void main(String args[]) throws Exception {
TestObj obj = new TestObj( 20 , " Rabbit " );
TestObj obj2;
System.out.println(obj);
ObjectOutputStream out = new ObjectOutputStream( new FileOutputStream(
" obj.out " ));
out.writeObject(obj);
out.close();
ObjectInputStream in = new ObjectInputStream( new FileInputStream(
" obj.out " ));
obj2 = (TestObj) in.readObject();
System.out.println(obj2);
}
}
class Data implements Serializable { // Data class is aslo declare as
// Serializable
public int data;
public Data() {
data = ( int ) (Math.random() * 100 );
}
}
class TestObj implements Serializable {
transient private int testInt; // testInt is declare as a transient element
private String testString;
private Data testData;
TestObj( int testInt, String testString) {
this .testInt = testInt;
this .testString = testString;
testData = new Data();
}
public String toString() {
String s;
s = Integer.toString(testInt) + " " + testString + " "
+ Integer.toString(testData.data);
return s;
}
}
public class WriteObject {
public static void main(String args[]) throws Exception {
TestObj obj = new TestObj( 20 , " Rabbit " );
TestObj obj2;
System.out.println(obj);
ObjectOutputStream out = new ObjectOutputStream( new FileOutputStream(
" obj.out " ));
out.writeObject(obj);
out.close();
ObjectInputStream in = new ObjectInputStream( new FileInputStream(
" obj.out " ));
obj2 = (TestObj) in.readObject();
System.out.println(obj2);
}
}
在本例中,testInt没有被还原,因为它被声明是transient。
可以在Serializable中显式地指定一种替换Externalizable的方法
private void wrtieObject(ObjectOutputStream stream) throws IOException;
private void readObject(ObjectInputStream stream) throws IOException,ClassNotFoundExcetion;
在其中可以指定完成默认的读写工作,通过调用
stream.defaultWriteObject();
stream.defaultReadObject();
stream.defaultWriteObject();
stream.defaultReadObject();