[英]Can't locate origin of null pointer exception
如何避免NullPointerExceptions
? 我試過使用try-catch
塊,但是沒有用。
我的程序應該從Google日歷獲取數據。 我得到了很多元素,但是這里僅以一個元素為例...
for (Iterator<?> i = eventsToday.iterator(); i.hasNext();) {
Component component = (Component) i.next();
String Attachement=null;
if(component.getProperty(Property.ATTACH).toString().trim()!=null){
Attachement=component.getProperty(Property.ATTACH).toString();
}
}
有人可以幫我這個忙。
測試component.getProperty() == null
是否會導致null指針異常是由於在空對象上調用了toString()
而導致的。 以下示例將起作用。 (將Object o
替換為getProperty()
返回的實型)
String Attachment;
Object o = component.getProperty(Property.ATTACH);
if(o != null) {
Attachment = component.getProperty(Property.ATTACH).toString();
}
問題可能是
component.getProperty(Property.ATTACH)
返回null
只需添加一些檢查代碼
if (component.getProperty(Property.ATTACH)) {
Attachement = component.getProperty(Property.ATTACH).toString();
}
您可能想要緩存component.getProperty(Property.ATTACH)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.