java对象序列化

对象序列化:就是将一个对象转换为二进制的数据流,如果一个类的对象要想实现对象序列化,则对象所在的类必须实现Serializable接口。这个接口没有任何方法,只是作为一个标识,标识本类的对象具备了序列化的能力而已。

如果要想完成对象的序列化,则还要依靠ObjectOutputStream类和ObjectInputStream类,前者属于序列化操作,而后者属于反序列化操作。

transient关键字表示不希望进行序列化

如果要同时对多个对象进行序列化,则使用对象数组

import java.io.*;

class Person2 implements Serializable
{
 private transient String name;
 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 public int getAge() {
  return age;
 }

 public void setAge(int age) {
  this.age = age;
 }

 private int age;
 
 public Person2(String name,int age)
 {
   this.name=name;
   this.age=age;
 }
 
 public String toString()
 {
  return "姓名:"+this.name+"年龄:"+this.age;
 }
}

public class SerializableDemo {
 public static void main(String args[]) throws Exception
 {
        Person2[] p3={new Person2("张三",55),new Person2("李四",31)};
     ser(p3);
     Person2 p4[]=(Person2[])reser(p3);
     print(p4);
 } 
    public static void ser(Object obj) throws Exception
    {
     //序列化
   File file=new File("d:"+File.separator+"person.ser");
   ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream(file));
     oos.writeObject(obj);
     oos.close();
    }
    public static Object reser(Object obj) throws Exception
    {
     File file=new File("d:"+File.separator+"person.ser");
      //反序列化
     ObjectInputStream ois=new ObjectInputStream(new FileInputStream(file));
  Object temp=ois.readObject();     
        return temp;
    }
    public static void print(Person2 p[])
    {
     for(Person2 p2:p) 
     {
      System.out.println(p2.getName()+" "+p2.getAge());
     }
    }
}

原文地址:https://www.cnblogs.com/jinzhengquan/p/1948436.html