-2

can anyone help on the below issue in EWS,

I am getting an error java.lang.ClassCastException: microsoft.exchange.webservices.data.property.complex.ItemAttachment cannot be cast to 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();
    }
}
jegankkk
  • 3
  • 1
  • Can you be more specific about which part of the error message is confusing you? Can you let us know what you have tried in order to fix it after doing some research on that exception? – takendarkk Aug 29 '18 at 21:14
  • getting the above casting exception in this line FileAttachment iAttachment = (FileAttachment) it; – jegankkk Aug 29 '18 at 21:19

1 Answers1

1

Both FileAttachment and ItemAttachment are direct subclasses of Attachment class. It seams some of the attachments are instance of ItemAttachment and you are trying to cast them to FileAttachment. Since FileAttachment class is not a subclass of ItemAttachment you cannot cast to it.

With an example:

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

in this example you cannot

guleryuz
  • 2,714
  • 1
  • 15
  • 19