我想知道为什么我的解码过程会造成一些麻烦:
- 我将 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;
}
}
最佳答案
isLogin
对 String
对象进行身份比较。
在第一种情况下,您多次使用相同的字符串文字 "p1"
,并且 ==
给出 true
因为字符串
池化。
解码后,您会得到一个新的String
,它等于
“p1”,但不会是相同的String
对象。
因此,在 isLogin
方法中使用 equals
而不是 ==
。
关于java - 解码时对象方法出现问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37073885/