java中集合如何的序列化和反序列化

两天儿 发布于 2016/05/04 14:36
阅读 480
收藏 0

父类没有实现序列化接口

public class Student{
/**
* 没有是实现序列化接口的父类
*/
private int age;


public int getAge() {
return age;
}


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

public Student(int age) {
super();
this.age = age;
}


public Student() {

}


@Override
public String toString() {
return "age=" + this.age;
}

}

//子类继承父类并实现序列化接口
public class NewStudent extends Student implements Serializable{
public NewStudent(int age, String name) {
super(age);
this.name = name;
}


public NewStudent(int age) {
super(age);
}


/**
* Serializable sign
*/
private static final long serialVersionUID = 7970852171542707101L;

private String name;


public String getName() {
return name;
}


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


@Override
public String toString() {
return "NewStudent [name=" + name + "," +super.toString() +"]";
}
}

//自此类中调用子类,并以集合类型实例变量的形式引用
public class Teacher implements Serializable{
/**
* serializable sign
*/
private static final long serialVersionUID = 793763154946358103L;


private String name;

private NewStudent newstudent;

private List<NewStudent> student=new ArrayList<NewStudent>();


public List<NewStudent> getStudent() {
return student;
}


public void setStudent(List<NewStudent> student) {
this.student = student;
}


public String getName() {
return name;
}


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


public NewStudent getNewstudent() {
return newstudent;
}


public void setNewstudent(NewStudent newstudent) {
this.newstudent = newstudent;
}


public Teacher(String name, NewStudent newstudent) {
super();
this.name = name;
this.newstudent = newstudent;
}


public Teacher(String name, List<NewStudent> student) {
super();
this.name = name;
this.student = student;
}



@Override
public String toString() {
return "Teacher [name=" + name + ", student=" + student + "]";
}

}
//在主方法中测试序列化和反序列化过程。

public class TestSeria {
public static void main(String[] args) {
List<NewStudent> student_teacher=new ArrayList<NewStudent>();
student_teacher.add(new NewStudent(13,"tom"));
student_teacher.add(new NewStudent(12, "jone"));

Teacher teacher=new Teacher("zhang",student_teacher);

// Teacher teacher2=new Teacher("wang",new NewStudent(15,"tom"));

try {
ObjectOutputStream read=new ObjectOutputStream(new FileOutputStream("orfg"));
read.writeObject(teacher);
System.out.println(teacher);
System.out.println("is read sign......");

read.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

try {
ObjectInputStream write=new ObjectInputStream(new FileInputStream("orfg"));
teacher=(Teacher)write.readObject();

System.out.println(teacher);

write.close();
System.out.println("is write sign.....");

} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
//结果


此时反序列化结果输出就出现父类的age属性为0,这是为什么



加载中
返回顶部
顶部