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
помогает ограничить всю передаваемую информацию?
Подклассы не должны реализовывать сериализуемое право?
- Получает ли получательсериализованные данные должны знать о классах, для которых он десериализует данные?