有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

解组时对象方法的java问题?

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

  1. 我将java对象保存在xml文件中
  2. 我从xml文件加载java对象

一旦完成,我的java对象(ClassMain.java)的方法中就会出现奇怪的行为

实际上,method isLogin()在返回true之前返回false(ClassMain.java)。有什么想法吗

MainClass

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;
}
}

共 (1) 个答案

  1. # 1 楼答案

    isLoginString对象进行身份比较

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

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

    因此,在isLogin方法中使用equals而不是==

    How do I compare strings in Java?