解组时对象方法的java问题?
我想知道为什么我的解组过程会带来一些麻烦:
- 我将java对象保存在xml文件中李>
- 我从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 楼答案
isLogin
对String
对象进行身份比较在第一种情况下,您多次使用相同的字符串文字
"p1"
,并且==
由于String
池而给出true
解组后,您会得到一个新的
String
,它是equals
“p1”,但不会是相同的String
对象因此,在
isLogin
方法中使用equals
而不是==
见How do I compare strings in Java?