【发布时间】:2016-05-06 13:39:01
【问题描述】:
我想知道为什么我的解组过程会引起一些麻烦:
- 我将我的 java 对象保存在一个 xml 文件中。
- 我从 xml 文件加载我的 java 对象
完成后,我的 java 对象 (ClassMain.java) 的方法中会出现奇怪的行为。
确实,method isLogin() 在返回 true 之前返回 false(ClassMain.java。有什么想法吗?
主类
public static void main(String[] args) {
Player p1 = new Player();
p1.setLogin("p1");
p1.setMdp("mdp1");
try {
//Test : verify that player's login is 'p1' (return true)
System.out.println(p1.isLogin("p1"));
marshaling(p1);
Player pfinal =unMarshaling();
//Test : verify that player's login is 'p1' (return False ?why?)
System.out.println(pfinal.isLogin("p1"));
} catch (JAXBException e) {
e.printStackTrace();
}
}
private static Player unMarshaling() throws JAXBException {
JAXBContext jaxbContext = JAXBContext.newInstance(Player.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
Player player = (Player) jaxbUnmarshaller.unmarshal( new File("C:/Users/Public/player.xml") );
return player;
}
private static void marshaling(Object o) throws JAXBException {
JAXBContext jaxbContext = JAXBContext.newInstance(Player.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
jaxbMarshaller.marshal(o, new File("C:/Users/Public/player.xml"));
}}
播放器类
@XmlRootElement(name = "joueur")
@XmlAccessorType (XmlAccessType.FIELD)
public class Player{
@XmlAttribute
private String login;
public Player() {
}
public String getLogin() {
return this.login;
}
public void setLogin(String login) {
this.login = login;
}
public boolean isLogin(String n){
if(this.login == n)
return true;
else
return false;
}
}
【问题讨论】:
-
不用看,请不要用等号运算符
if(this.login == n)比较字符串,改用equals方法。 -
"在返回 true 之前返回 false" - 这是什么意思?您是否遇到任何异常或只是奇怪的行为?
标签: java xml jaxb marshalling unmarshalling