繁体   English   中英

无法找到空指针异常的起源

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM