感觉像是一个非常基本的问题,但我无法理解它。
有一个 PriceGroup 类,没有构造函数,我要为其创建对象。
class SmallPortfolio{
String id;
// all the investments (stocks) belonging to this portfolio.
List<Investment> invList = new ArrayList<Investment>();
}
现在,在一个单独的类中,我正在创建一个名为 Spor 的 SmallPortfolio 对象。
//
String id = InstanceID.getTextNormalize(); //this value is taken from an element from jdom.
SmallPortfolio Spor;
Spor.id = id;
//some code that creates a list of investments
//some code that creates a list of SmallPortfolio objects
在java中,如何为空对象的字段提供通过NullPointerException获取的值? 另一种解决方案是以某种方式声明一个不为 null 的 SmallPortfolio 对象。
这是一个奇怪的问题,但我正在使用的测试程序无法修改,并且它没有 SmallPortfolio 的构造函数。
最佳答案
除非您自己定义一些构造函数,否则 Java 会自动为您创建一个默认的无参构造函数。所以你可以写:
SmallPortfolio smallPort = new SmallPortfolio();
但是,在您的情况下,SmallPortfolio 类的作者可能应该提供一个临时构造函数:
class SmallPortfolio{
private final String id;
// all the investments (stocks) belonging to this portfolio.
private final List<Investment> investments = new ArrayList<Investment>();
public SmallPortfolio(String id) {
this.id = id;
}
//getters + methods to add / remove investments
}
关于Java - 给空对象的字段一个值或声明没有构造函数的对象不为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13329407/