我一直在玩 java 中的序列化 XML 并且有点卡住了。当我运行这个程序时,我得到了两个异常,我不确定原因是什么:
java.lang.InstantiationException: Ship
Continuing ...
java.lang.Exception: XMLEncoder: discarding statement XMLEncoder.writeObject(Ship);
Continuing ...
我怀疑我尝试序列化的类有问题,因为当我使用互联网示例时,它工作正常。
有人可以指出我犯了什么错误。
主要的:
public class Main {
private static final String XMLLocation = "xmlTest.xml";
static ObjectSerializationToXML serializer = new ObjectSerializationToXML();
public Main() {
// TODO Auto-generated constructor stub
}
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
Ship ship = new Ship("name", "324");
serializer.serializeObjectToXML(XMLLocation, ship);
}
}
对象序列化-XML 类:
import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class ObjectSerializationToXML {
/**
* <span id="IL_AD10" class="IL_AD">This method</span> saves (serializes) any java bean object into xml file
*/
public void serializeObjectToXML(String xmlFileLocation,
Object objectToSerialize) throws Exception {
FileOutputStream os = new FileOutputStream(xmlFileLocation);
XMLEncoder encoder = new XMLEncoder(os);
encoder.writeObject(objectToSerialize);
encoder.close();
}
/**
* Reads Java Bean Object From XML File
*/
public Object deserializeXMLToObject(String xmlFileLocation)
throws Exception {
FileInputStream os = new FileInputStream(xmlFileLocation);
XMLDecoder decoder = new XMLDecoder(os);
Object deSerializedObject = decoder.readObject();
decoder.close();
return deSerializedObject;
}
}
要序列化的对象(导致异常的我的对象):
public class Ship {
private String name;
private String yearBuilt;
public Ship(String name, String yearBuilt) {
this.name = name;
this.yearBuilt = yearBuilt;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getYearBuild() {
return yearBuilt;
}
public void setYearBuild(String yearBuild) {
this.yearBuilt = yearBuild;
}
@Override
public String toString() {
return "ship [name=" + name + ", yearBuilt=" + yearBuilt + "]";
}
}
要序列化的对象(来自互联网的示例):
public class MyBeanToSerialize {
private String firstName;
private String lastName;
private int age;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}