我有以下类允许我序列化程序中的对象:
import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
public class Persistor<T> {
private T data;
public void save(T data, String file) {
try {
FileOutputStream os = new FileOutputStream(file);
XMLEncoder encoder = new XMLEncoder(os);
encoder.writeObject(data);
encoder.close();
} catch(FileNotFoundException e) {
System.out.println("File not found");
}
}
@SuppressWarnings({ "unchecked", "finally" })
public T read(String file) {
try {
FileInputStream fis = new FileInputStream(file);
XMLDecoder decoder = new XMLDecoder(fis);
data = (T)decoder.readObject();
decoder.close();
} catch(FileNotFoundException e) {
System.out.println("File not found");
} finally {
return data;
}
}
}
问题是我有像学生这样的类的业务逻辑包,似乎我需要一个空的构造函数public Student() {}
才能让程序工作:
package logic;
public class Student {
private String name;
public Student(String name) {
this.name = name;
} public Student() {} // empty constructor
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String toString() {
return name;
}
}
如果我取出空的构造函数,控制台上会出现以下异常:
java.lang.InstantiationException: logic.Student
Continuing ...
java.lang.IllegalStateException: The outer element does not return value
Continuing ...
有没有办法解决这个问题,我的意思是没有空的构造函数?因为我还有 7 个类,每个人都需要有自己的空构造函数。