找不到空指针异常的来源

VIC*_*TSC 0 java nullpointerexception

我怎么能避免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();
    }
}
Run Code Online (Sandbox Code Playgroud)

有人可以帮我这个.

sec*_*ula 7

测试component.getProperty() == null空指针异常是否是由于toString()在空对象上调用.以下示例将起作用.(替换Object o为返回的实际类型getProperty())

String Attachment;
Object o = component.getProperty(Property.ATTACH);
if(o != null) {
   Attachment = component.getProperty(Property.ATTACH).toString();
}
Run Code Online (Sandbox Code Playgroud)