【问题标题】:Issue with Object's Method when unmarshalling? [duplicate]解组时对象的方法有问题吗? [复制]
【发布时间】:2016-05-06 13:39:01
【问题描述】:

我想知道为什么我的解组过程会引起一些麻烦:

  1. 我将我的 java 对象保存在一个 xml 文件中。
  2. 我从 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


【解决方案1】:

isLoginString 对象进行身份比较。

在第一种情况下,您多次使用相同的字符串文字 "p1",并且由于 String 池化,== 给出了 true

解组后,您会得到一个新的String equals "p1",但不会是相同的 String 对象。

所以在你的isLogin 方法中使用equals 而不是==

How do I compare strings in Java?

【讨论】:

  • 谢谢伯杰!祝你有美好的一天
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多