【发布时间】:2015-03-06 08:07:28
【问题描述】:
我有一个public static void 方法,它从某个来源读取信息。然后我使用这些设置方法来保存这些信息。 get/set 方法在一些单独的public 类中声明。 get 方法在我还定义了 set 方法的类中工作正常,但在任何其他类/方法中都不起作用。我得到的只是值null。我不知道为什么...有人可以帮帮我吗?
public static void InformationFinder() {
String identificationID = null;
String flag = null;
String nickname = null;
// part to read the informations (saved in the variables above)
UserInfo user = new UserInfo();
user.setIdentificationID(identificationID);
user.setVorname(flag);
user.setNachname(nickname);
// shows me up the correct ID
System.out.println("Tell me the ID: " + user.getIdentificationID());
}
public class UserInfo {
public String identificationID;
public String flag;
public String nickname;
public UserInfo () {
public String getIdentificationID() {
return Nachname;
}
public String getFlag() {
return flag;
}
public String getNickname() {
return nickname;
}
// set Methoden
public void setIdentificationID(String identID) {
this.identificationID = identID;
}
public void setFlag(String flag) {
this.flag= flag;
}
public void setNickname (String nickname) {
this.nickname = nickname;
}
}
public static void main(String[] args) {
UserInfo user = new UserInfo();
// shows me only null as result
System.out.println(UserInfo.getIdentificationID());
}
我知道问题可能是由于对象的第二次实例化。但是我发现没有其他方法可以在 'main()' 函数中使用 get 方法。
【问题讨论】:
-
你试过调试你的代码吗?
-
设置断点并单步执行您的代码。考虑将 UserInfo 类中的字段设为私有,因为无论如何您都在公开 getter/setter。
-
你得到 null 因为值真的是
null! . -
您没有为用户对象设置任何值。我在下面的帖子中添加了一个解决方案。试试这个,让我知道。
-
可能想在 main 中调用 InformationFinder() 但不确定为什么 SO 代码模板将其视为类名。