2

I'm using a JOINED inheritance strategy for a class hierarchy which as follows:

abstract super class Product

concrete sub class Type1Product extends Product

concrete sub class Type2Product extends Product

Now i want to make a REST endpoint which allows users to POST data and for it to be parsed as a specific subclass of product, making sure its the same endpoint for any type of product. So something like the following:

@RequestMapping(method = POST, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
    public Product save(@Valid Product product) {
        // ...
        return product;
    }

Currently when I try to post I get an error saying I can't initialize an abstract class, since Spring is trying to create a Product instance as opposed to an instance of the correct subtype.

Is what I'm trying to do possible? If not then what is the best practice or convention when making endpoints like this for an inheritance hierarchy?

2
  • if you keep your product class concrete and return specific product at the time of returning that may solve the problem Commented Aug 21, 2017 at 9:41
  • But that would be incorrect conceptually since Product shouldn't exist on its own. I don't mind changing this approach, just wondering how a situation like this is normally tackled. Commented Aug 21, 2017 at 9:45

1 Answer 1

1

let us see what you are trying to do, you are trying to deserialize an object and you are telling jackson that its Product which is your abstract class, and you want jackson to find by itself what the concrete class.

this could not be achieved and it make sense , lets say jackson could be built to figure out what which concrete class based on the additional attributes, ok so suppose we have two concrete classes with no additional attributes, here how jackson gonna find out what is the concrete class?

when specifying the deserialized class default constructor will be called so if your class is abstract that will not work, you need an endpoint for each concrete class or you need a DTO and model mapper, your DTO can contain the concrete class and all the possible attributes and your model mapper should rely in the concrete class indicated in your DTO, using this approach you can do it in one endpoint.

Sign up to request clarification or add additional context in comments.

2 Comments

I'm not actually using Jackson but I get what you're saying and I thought the same thing, so I suppose separate endpoints/controllers is the best approach?
@user3690467 what are you using? spring by default uses jackson, and you could go for DTO/modelmapper, i find it a delegate solution

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.