在java中实现序列化时出现的问题
import java.io.Serializable;
public class Employee implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private String name;
private int id;
private HHPEmployee hhp;
public Employee(String name, int id) {
this.id = id;
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public HHPEmployee getHhp() {
return hhp;
}
public void setHhp(HHPEmployee hhp) {
this.hhp = hhp;
}
}
子类
import java.io.Serializable;
public class HHPEmployee extends Employee{
/**
*
*/
private static final long serialVersionUID = 1L;
public HHPEmployee(String name, int id) {
super(name,id);
}
private String name;
private int id;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
序列化对象-
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
public class stringObjects {
public static void main(String[] args) {
HHPEmployee e = new HHPEmployee("G", 2000);
Employee emp = new Employee("A", 4876);
emp.setHhp(e);
FileOutputStream file = null;
ObjectOutputStream str = null;
try {
file = new FileOutputStream("src/EmployeeByteStream.ser");
str = new ObjectOutputStream(file);
str.writeObject(emp);
str.close();
file.close();
System.out.println("object has been serialized");
// emp.setId(2000);
} catch (IOException ex) {
// TODO Auto-generated catch block
ex.printStackTrace();
}
}
}
反序列化字节流-
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
public class deserialObject {
public static void main(String[] args) {
FileInputStream file;
ObjectInputStream in;
try {
file = new FileInputStream("src/EmployeeByteStream.ser");
in = new ObjectInputStream(file);
Employee emp = (Employee) in.readObject();
System.out.println(emp.getId());
System.out.println(emp.getName());
System.out.println(emp.getHhp().getName());
System.out.println(emp);
} catch (IOException | ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
为什么即使我正在设置值,我仍然会得到
null
的System.out.println(emp.getHhp().getName());
另外,在反序列化字节流时,在我使用
serialVersionUID
的地方没有。那么serialVersionUID
如何帮助限制要传输的整个信息呢子类不需要实现序列化,对吗
- 序列化数据的接收者是否需要知道他正在反序列化数据的类李>
# 1 楼答案
首先,不要使用Java序列化,这很糟糕。要回答您的问题:
HHPEmployee
name
字段。与序列化无关。试试看,不要用李>serialVersionUID
是Java序列化机制使用反射访问的神奇常量。类似地使用的其他字段和方法有serialPersistentFields
、readObject
、readObjectNoData
、writeObject
、readResolve
和writeReplace
李>ObjectInputStream
本身只是在堆栈中进行一次遍历,以找到第一个非引导类装入器。RMI(默认情况下不是现在!)将获取流选择的任何随机URL,并从那里开始加载类李>我还强烈建议使用try with resource