gpt4 book ai didi

java - 在我的程序中传递私有(private)实例属性对象

转载 作者:行者123 更新时间:2023-12-01 17:23:32 24 4
gpt4 key购买 nike

谁能告诉我为什么我的属性对象为空?我是否必须将其传递到方法中,还是有更好的方法?如果我需要在包之间传递属性对象怎么办?谢谢!

public class Test {
private Properties properties = null;

public static void main (String[] args) {
testObject = new Test();
Properties properties = new Properties(); // Then load properties from fileInputStream sucessfully

utilityMethod();
}

private void utilityMethod() {
properties.getProperty("test"); // Why do I get a null pointer exception?
}
}

最佳答案

在 main() 中,对“属性”的赋值是局部变量,而不是实例字段。

如果您想设置该字段,可以这样做:

private Properties properties = new Properties();

或者在这样的构造函数中:

 public Test() {
properties = new Properties();
}

或者,如果您希望类 Test 的所有实例都有一个值,如下所示:

 private static Properties properties = new Properties();

关于java - 在我的程序中传递私有(private)实例属性对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16805149/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com