I have the following class that allows me to serialize objects in my program:
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;
}
}
}
The thing is that I have my bussiness logic package with classes like student and it seems like I need to have an empty constructor public Student() {} to get the program working:
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;
}
}
If I take out the empty constructor, the following exceptions appear on the console:
java.lang.InstantiationException: logic.Student
Continuing ...
java.lang.IllegalStateException: The outer element does not return value
Continuing ...
Is there any way to fix this stuff, I mean by not having the empty constructor? Because I have like 7 more classes where everyone needs to have it's own empty constructor.