1

I would like to know why my unmarshalling process cause some troubles:

  1. I save my java object in a xml file.
  2. I load my java object from the xml file

Once that's done, strange behaviour occurs in the method of my java object (ClassMain.java).

Indeed the method isLogin() returns false just before it returns true (ClassMain.java. Any ideas?

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

Player Class

@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;
}
}
Panda
  • 6,955
  • 6
  • 40
  • 55
R.Simba
  • 11
  • 1
  • without further looking, please don't compare strings with the equal operator `if(this.login == n)`, use the `equals` method instead. – A4L May 06 '16 at 13:48
  • "returns false just before it returns true" - what does that mean? Do you get any exceptions or just strange behavior? – MaxG May 06 '16 at 13:48

1 Answers1

2

isLogin makes identity comparison on String objects.

In the first case, you use several times the same String literal "p1", and the == gives true because of the String pooling.

After unmarshalling, you get a new String which equals "p1", but won't be the same String object.

So use equals instead of == in your isLogin method.

See How do I compare strings in Java?

Community
  • 1
  • 1
Arnaud
  • 17,229
  • 3
  • 31
  • 44