感覺像是一個超級基本問題,但我無法用頭來包圍它。Java - 爲null對象的字段賦值或聲明沒有構造函數的對象不爲null
有一個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中,你如何給null對象的字段值得到NullPointerException? 另一種解決方案是以某種方式聲明一個不爲null的SmallPortfolio對象。
這是一個奇怪的問題,但我使用的測試程序無法修改,它沒有SmallPortfolio的構造函數。
如果這些代碼是字段聲明而非局部變量聲明,則給出的代碼將被編譯。 –
@JonSkeet:這是正確的。但是,第三行('Spor.id = id;')不能在塊外部使用,而第一行('String id = InstanceID.getTextNormalize();')可能用於字段聲明,看起來不是。 – Thilo
良好的捕獲 - 沒有看到這一點。 (這對OP的術語非常困惑:「你如何給一個空對象的字段賦值」,這表明他們可以對變量,值,引用,對象等進行重要的教訓。) –