我正在尝试序列化一个引用另一个Object作为实例变量的Object。我遵循常见的方法,但是我不能在main()方法中检索第二个Object(它是不可序列化的)。这是我的代码:
public class Car {
String type;
int speed;
public Car(String s, int v){
type = s;
speed = v;
}
}
public class Employee implements Serializable {
String name;
int Id;
transient Car car;
public Employee(String s, int i, Car c){
name = s;
Id = i;
car = c;
}
private void writeObject(ObjectOutputStream os){
try {
os.defaultWriteObject();
os.writeObject(car);
} catch (IOException e) {
e.printStackTrace();
}
}
private void readObject(ObjectInputStream is){
try {
is.defaultReadObject();
car = (Car)is.readObject();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
主要方法:
public static void main(String[] args) {
Car c = new Car("noType", 100);
Employee e = new Employee("Aris", 1, c);
try {
FileOutputStream fo = new FileOutputStream("save.txt");
ObjectOutputStream out = new ObjectOutputStream(fo);
out.writeObject(e);
out.close();
} catch (IOException e1) {
e1.printStackTrace();
}
try {
FileInputStream fi = new FileInputStream("save.txt");
ObjectInputStream in = new ObjectInputStream(fi);
Employee emp = (Employee) in.readObject(); // Comment
System.out.println(emp.car.speed);
in.close();
}catch (ClassNotFoundException e1) {
e1.printStackTrace();
}
catch (IOException e1) {
e1.printStackTrace();
}
}
在第二个try块的"Comment"行上,它抛出一个nullPointerException。它无法以这种方式保存Car对象。我该怎么办才能克服它?当然,我希望Car类保持不可序列化。如果更喜欢保存Car对象的instrance变量,并借助它们及其构造函数重新创建它,我如何保存(和检索)String属性?
更新:
当试图只保存int实例变量时,它是有效的。这次的相关方法是:
private void writeObject(ObjectOutputStream os){
try {
os.defaultWriteObject();
os.writeInt(car.speed);
} catch (IOException e) {
e.printStackTrace();
}
}
private void readObject(ObjectInputStream is){
try {
is.defaultReadObject();
car = new Car("theNew", is.readInt());
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
但我的问题仍然是如何(或是否)保存整个对象。毕竟,我没有设法保存和检索字符串。WriteString()、ReadString()方法不存在。
行
car = (Car)is.readObject();
是错误的。汽车不可序列化。
解决方案:
使car可串行化,并删除行
使用MyCar对象,该对象仅可串行化用于ser/deser,并从MyCar创建汽车,请参见第3点。
创建一辆新车:Car=new Car();但是从哪里获取数据呢?(见第2点)
使用os.writeObject()和os.writeInt()等原语逐个捕获car的字段;
使用DataOutputStream ,使用您自己的自定义序列化
更新回答您的更新问题
字符串是一个对象,您可以用os.writeObject(car.type)序列化它
另请参阅ObjectOutputStream
使用解决方案4:的代码
private void writeObject(ObjectOutputStream os){
try {
os.defaultWriteObject();
os.writeObject(car.type);
os.writeInt(car.speed);
} catch (IOException e) {
e.printStackTrace();
}
}
private void readObject(ObjectInputStream is){
try {
is.defaultReadObject();
String type = (String) is.readObject();
int speed = is.readInt();
this.car = new Car(type, speed);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}