Java 设置和获取方法不起作用
我有一个公共的静态void方法,它从某些来源读取信息。然后我使用这些set方法来保存这些信息。get/set方法在一些单独的公共类中声明。get方法在我定义了set方法的类中运行良好,但在任何其他类/方法中都不起作用。我只得到null值。我不知道为什么。。。有人能帮我吗Java 设置和获取方法不起作用,java,get,set,Java,Get,Set,我有一个公共的静态void方法,它从某些来源读取信息。然后我使用这些set方法来保存这些信息。get/set方法在一些单独的公共类中声明。get方法在我定义了set方法的类中运行良好,但在任何其他类/方法中都不起作用。我只得到null值。我不知道为什么。。。有人能帮我吗 public static void InformationFinder() { String identificationID = null; String flag = 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方法的其他方法。我认为问题在于main方法中代码的以下部分-
UserInfo user = new UserInfo();
// shows me only null as result
System.out.println(UserInfo.getIdentificationID());
在上面的main方法代码中,您正在创建一个新的UserInfo。但是set方法不适用于此处创建的用户。此方法适用于其他对象。对同一对象使用set方法
在-public静态void InformationFinder函数中创建的UserInfo对象与在main方法中创建的UserInfo对象不同。当您在InformationFinder方法中设置一些用户属性时,如-
user.setIdentificationID(identificationID);
user.setVorname(flag);
user.setNachname(nickname);
在main方法中,还必须添加这些setter方法-
user.setIdentificationID(identificationID);
user.setVorname(flag);
user.setNachname(nickname);
希望这会有帮助。
非常感谢。您试过调试代码吗?设置断点并逐步完成代码。考虑在UsReFieldPrimes类中创建字段,因为您无论如何都暴露了GETS/SETTER。因为值实际上是NULL,所以NULL!您尚未为用户对象设置任何值。我在下面的帖子中添加了一个解决方案。试试这个,让我知道。可能想在main中调用InformationFinder,但不确定为什么代码模板会将其视为类名。感谢您的解决方案,但我没有主方法中没有的标识ID、标志和昵称的信息。很多答案都可以解决这个问题,例如,在main中调用InformationFinder函数,但是嘿,那么OP不会从某个地方学习,你必须提供它或使用虚拟信息。另一方面,没有办法摆脱空值。因为main方法中的用户与informatinFinder方法中的用户完全不同。好吧,因为main函数可以工作,但是当我需要另一个类中的另一个方法将信息写入数据库时会发生什么呢。在那里,我绝对无法访问标识ID、旗帜和昵称。我希望你知道我的意思。@Panther然后在main中使用它。你发布的代码似乎没有任何扫描器,只有空值