Jersey, JAXB and getting an objectextending an abstract class as a parameter
Posted
by
krajol
on Stack Overflow
See other posts from Stack Overflow
or by krajol
Published on 2012-11-02T15:50:54Z
Indexed on
2012/11/02
17:02 UTC
Read the original article
Hit count: 215
I want to get an object as a parameter of a POST request. I got an abstract superclass that is called Promotion and subclasses Product and Percent. Here's how I try to get a request:
@POST
@Consumes(MediaType.APPLICATION_XML)
@Produces(MediaType.APPLICATION_XML)
@Path("promotion/")
public Promotion createPromotion(Promotion promotion) {
Product p = (Product) promotion;
System.out.println(p.getPriceAfter());
return promotion;
}
and here's how I use JAXB in classes' definitions:
@XmlRootElement(name="promotion")
@XmlSeeAlso({Product.class,Percent.class})
public abstract class Promotion {
//body
}
@XmlRootElement(name="promotion")
public class Product extends Promotion {
//body
}
@XmlRootElement(name="promotion")
public class Percent extends Promotion {
//body
}
So the problem now is when I send a POST request with a body like this:
<promotion>
<priceBefore>34.5</priceBefore>
<marked>false</marked>
<distance>44</distance>
</promotion>
and I try to cast it to Product (as in this case, fields 'marked' and 'distance' are from Promotion class and 'priceBefore' is from Product class) I get an Exception:
java.lang.ClassCastException: Percent cannot be cast to Product.
It seems like Percent is chosen as a 'default' subclass. Why is that and how can I get an object that is a Product?
© Stack Overflow or respective owner