java.lang.ClassCastException:无法将ItemAttachment强制转换为FileAttachment

时间:2018-08-29 21:12:37

标签: java exchangewebservices

任何人都可以在EWS中解决以下问题

我遇到错误java.lang.ClassCastException:microsoft.exchange.webservices.data.property.complex.ItemAttachment无法转换为microsoft.exchange.webservices.data.property.complex.FileAttachment

    private static void readAttachment(ExchangeService service, Folder folder, int n) {
    ItemView view = new ItemView(n);
    FindItemsResults<Item> findResults;
    try {
    findResults = service.findItems(folder.getId(), view);
    System.out.println("findResults-->"+findResults.getTotalCount());


    for (Item item : findResults) {
        EmailMessage email;

            email = EmailMessage.bind(service, item.getId(), new PropertySet(BasePropertySet.IdOnly, ItemSchema.Attachments));
            System.out.println("email.getAttachments().getCount()-->"+email.getAttachments().getCount());
            //email.load();
            for (Attachment it : email.getAttachments()) {
                System.out.println(it.getName());
                FileAttachment iAttachment = (FileAttachment) it;
                //iAttachment.load( "C:\\FileLocation\\" + iAttachment .getName());
            }

    }
    } catch (ServiceLocalException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

1 个答案:

答案 0 :(得分:0)

FileAttachmentItemAttachment都是Attachment类的直接子类。它接缝了某些附件是ItemAttachment的实例,您正在尝试将它们强制转换为FileAttachment。由于FileAttachment类不是ItemAttachment的子类,因此无法强制转换为它。

举个例子:

public class Animal {  }
public class Dog extends Animal { }
public class Cat extends Animal { }

Animal a = new Dog();
Cat c = (Cat)a; // this line produces ClassCastException as in your case

在此示例中,您不能