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

来源:互联网 发布:家庭网络组网方案 编辑:程序博客网 时间:2024/06/11 08:18
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

代码如下:
  1. package com.bytecode.openexcel.util;
  2. import java.io.File;
  3. import java.io.FileInputStream;
  4. import java.io.FileNotFoundException;
  5. import java.io.FileOutputStream;
  6. import java.io.IOException;
  7. import java.io.ObjectInputStream;
  8. import java.io.ObjectOutputStream;
  9. public class TestSerializable {
  10.     public static void main(String[] args) {
  11.         Student st = new Student("zhangshang", 23);
  12.         Student su;
  13.         try {
  14.             ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(new File("c:/out.txt")));
  15.             oos.writeObject(st);
  16.             oos.close();
  17.             
  18.             ObjectInputStream ois = new ObjectInputStream(new FileInputStream(new File("c:/out.txt")));
  19.             su = (Student)ois.readObject();
  20.             System.out.println(su.toString());
  21.         } catch (FileNotFoundException e) {
  22.             e.printStackTrace();
  23.         } catch (IOException e) {
  24.             e.printStackTrace();
  25.         } catch (ClassNotFoundException e) {
  26.             e.printStackTrace();
  27.         }
  28.     }
  29. }
  30. class Student implements java.io.Serializable{
  31.     
  32.     private String name ;
  33.     private transient int age;
  34.     public Student(){
  35.         
  36.     }
  37.     
  38.     public Student(String name, int age){
  39.         this.name = name;
  40.         this.age = age;
  41.     }
  42.     
  43.     public String toString(){
  44.         return "the name is :" + name + "/nthe age is :" + age;
  45.         
  46.     }
  47. }

原创粉丝点击