1

I'm trying to load jsonObjects into object entities from a REST responses but when I try to cast the abstract object array into real objects I get the exception: EntityAbstract[] cannot be cast to Feed[]

Feed extends EntityAbstract so they are in the same family, and when I debug the returning entities they are instances of Feed, and not EntityAbstract - so I don't see why I'm not allowed to do the cast.

This is the cast method declaration (returning value)

public EntityAbstract[] fetchEntities (Class entityClass) throws Exception
{}

And when I retreive the entities I try to;

for (Feed feed : (Feed[]) ((NewsService) service).getResponse().fetchEntities(Feed.class))
{}

And this throws the exception. What am I supposed to do in order to hint the correct returning array?

Daniel
  • 3,726
  • 4
  • 26
  • 49
  • 2
    Don't cast the array but the objects inside the array. Maybe look here too : http://stackoverflow.com/questions/395030/quick-java-question-casting-an-array-of-objects-into-an-array-of-my-intended-cl – singe3 Aug 20 '14 at 12:40

1 Answers1

1

An array of abstract class elements cannot be cast to an array of a specific type, but you can cast the individual elements as needed:

for (EntityAbstract af : (EntityAbstract[]) ((NewsService) service).getResponse().fetchEntities(Feed.class)) {
    Feed feed = (Feed)af;
    ...
}
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523