经过一小时的使用Java中的XMLEncoder
的wiki和约定后,我仍然无法使用XMLEncoder序列化我的SystemSnapshot
类。谁能告诉我出了什么问题?我的资源如下:
package core;
import gui.SceneManager;
import java.io.Serializable;
/**
*
* @author Subhra
*/
public class SystemSnapshot implements Serializable{
private static final long serialVersionUID = -6637378268413872760L;
private final School school;
private final User[] users;
private final String colorName;
public SystemSnapshot(){
school = SessionManager.getSchool();
users = UserStore.getUsers();
colorName = SceneManager.getColor();
}
public SystemSnapshot(School school, User[] users, String c) {
this.school = school;
this.users = users;
this.colorName = c;
}
public School getSchool() {
return school;
}
public User[] getUsers() {
return users;
}
public String getColorName() {
return colorName;
}
}
终端没有错误。但输出是这样的:
<?xml version="1.0" encoding="UTF-8"?>
<java version="1.8.0_40" class="java.beans.XMLDecoder">
<object class="core.SystemSnapshot"/>
</java>
任何?
在jtahlborn的回答之后,我想出了并添加了所有的吸气剂和二传手。现在我得到两种类型的输出。 案例1:
XMLEncoder xml = new XMLEncoder(new FileOutputStream("try.xml"));
School ss = new School("S");
ss.addSubject(new Subject("BEnals"));
ss.addTeacher(new Teacher("Nil","T0",21,5000,new Subject("S")));
ss.addClass(new Standard(1,1));
ss.addStudent("STU0");
User u = new User(UserType.ADMIN,"Subhra","subhra","itsveryconfidential");
SystemSnapshot ss2 = new SystemSnapshot(ss,new User[]{u},"A string");
xml.writeObject(ss2);
xml.close();
正在产生正确的输出。而 案例2:
XMLEncoder oos = new XMLEncoder(new FileOutputStream("data.base"));
SystemSnapshot ss = new SystemSnapshot(SessionManager.getSchool(),UserStore.getUsers(),SceneManager.getColor());
oos.writeObject(ss);
oos.close();
仍在生成上面显示的输出。怎么办?
SessionManager
和UserStore
SessionManager.java
package core;
import core.User.UserType;
public class SessionManager {
private static User currentuser;
private static School school;
public static void setSchool(School schol) {
school = schol;
}
public static School getSchool() {
return school;
}
public static User getCurrentuser() {
return currentuser;
}
public static void setCurrentuser(User currentuser) {
SessionManager.currentuser = currentuser;
}
public static UserType getCurrentUserType(){
return currentuser.getType();
}
}
UserStore.java
package core;
public class UserStore {
private static User[] users = new User[0];
public static User[] getUsers() {
return users;
}
public static void setUsers(User[] users) {
UserStore.users = users;
}
public static void addUser(User u) {
users = new BIO<User>().addToArray(users,u);
}
public static void removeUser(User u) {
users = new BIO<User>().removeFromArray(users,u);
}
public static User getUser(String username){
for(User u : users){
if(u.getUsername().equals(username)){
return u;
}
}
return null;
}
}
怎么了?
答案 0 :(得分:0)
我的猜测是你的SystemSnapshot不是一个有效的java bean,因为它没有你的属性的setter。 XMLEncoder没有像普通序列化那样做的魔法,它需要有效的java bean(所有属性的getter和setter)。