java.io.Serializable
对象要输入输出,请用ObjectInputStream ObjectOutputStream
那么好吧 你的对象implements Serializable 先
为什么要对象序列化呢?下面的例子
每个对象在memory中都有自己的序列号,而不是内存地址,因为对象加载的时候,内存地址很可能会改变,而且在网络中的不同的计算机传递对象的时候,根据什么来标志对象呢,要用序列号,那么好吧,序列化先。
下例中的 harry在memory中只有一份,在a,b中怎么来表示他们都拥有harry呢?引用序列号啊
对象要输入输出,请用ObjectInputStream ObjectOutputStream
那么好吧 你的对象implements Serializable 先
为什么要对象序列化呢?下面的例子
每个对象在memory中都有自己的序列号,而不是内存地址,因为对象加载的时候,内存地址很可能会改变,而且在网络中的不同的计算机传递对象的时候,根据什么来标志对象呢,要用序列号,那么好吧,序列化先。
下例中的 harry在memory中只有一份,在a,b中怎么来表示他们都拥有harry呢?引用序列号啊
package xml;
import java.io.Serializable;
import java.util.Date;
import java.util.GregorianCalendar;
import java.io.*;
public class ObjectStreamTest {
public static void main(String[] args){
Employee harry=new Employee("harry",2300,1919,1,1);
Manager a=new Manager("a",8800,1919,1,1);
a.setSecretary(harry);
Manager b=new Manager("b",8800,1919,1,1);
b.setSecretary(harry);
Employee[] staff=new Employee[3];
staff[0]=harry;
staff[1]=a;
staff[2]=b;
try{
ObjectOutputStream out=new ObjectOutputStream(new FileOutputStream("ObjectStream.txt"));
out.writeObject(staff);
out.close();
ObjectInputStream in=new ObjectInputStream(new FileInputStream("ObjectStream.txt"));
Employee[] newStaff=(Employee[])in.readObject();
in.close();
for(Employee e:newStaff)
System.out.println(e);
}catch(Exception e){}
}
}
class Employee implements Serializable{
private String name;
private double salary;
private Date hireDay;
public Employee(){}
public Employee(String n,double s,int y,int m,int d){
this.name=n;
this.salary=s;
GregorianCalendar calendar=new GregorianCalendar(y,m-1,d);
this.hireDay=calendar.getTime();
}
public String getName(){
return this.name;
}
public double getSalary(){
return this.salary;
}
public Date getHireDay(){
return this.hireDay;
}
public String toString(){
return getClass().getName()+"[name="+name+",salary="+this.salary+",hireday="+this.hireDay+"]";
}
}
class Manager extends Employee{
private Employee secretary;
public Manager(String n,double s,int year,int month,int day){
super(n,s,year,month,day);
secretary=null;
}
public void setSecretary(Employee s){
this.secretary=s;
}
public String toString(){
return super.toString()+"[secretary="+secretary+"]";
}
}