您的位置:首页 > 编程语言 > Java开发

JAVA基础学习篇----对象串行化及Transient关键字的使用

2009-01-08 18:07 591 查看
http://blog.csdn.net/scruffybear/archive/2007/12/03/1914586.aspx
http://blog.csdn.net/geggegeda/archive/2008/07/25/2709822.aspx
上面两篇文章看过后对对象串行化及Transient关键字的使用有了一定的理解
总之:串行化即对象序列化的类必须实现Serializable接口,序列化即是将创建的对象能够保存起来,将来要使用的时候再拿出来,如果对象的某个成员不想序列化,那么声明为transient。
如下类:Student
在测试类中创建Student对象,然后通过ObjectOutputStream将对象的信息写入文件中。
要用的时候再拿出来并强制转化为Student对象,输出。

数据成员:age不定义为transient时,测试结果输出
the name is :zhangshang
the age is :23

而定义为transient时输出为:
the name is :zhangshang
the age is :0

代码如下:
package com.bytecode.openexcel.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class TestSerializable {

public static void main(String[] args) {
Student st = new Student("zhangshang", 23);
Student su;
try {
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(new File("c:/out.txt")));
oos.writeObject(st);
oos.close();

ObjectInputStream ois = new ObjectInputStream(new FileInputStream(new File("c:/out.txt")));
su = (Student)ois.readObject();
System.out.println(su.toString());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}

}

class Student implements java.io.Serializable{

private String name ;
private transient int age;
public Student(){

}

public Student(String name, int age){
this.name = name;
this.age = age;
}

public String toString(){
return "the name is :" + name + "/nthe age is :" + age;

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: