Question

I have the following abstract model class

public abstract class Thing {
    private String id;
    private String name;
   ...
}

3 other model classes extends it. Let's call them Rock, Paper, Scissor. Example with Paper:

public class Paper extends Thing {
    private String paperFormat;
    ...
}

I now have the following CRUD-related interface to implement:

public interface ThingOperations {
    public String addThingForm();
    public String processAddThing(Thing thing, BindingResult result);
   ...
}

Here, processAddThing() is what processes a form model (addThingForm() initializes the form). Now let's say I want to create a Controller related to each concrete class (RockController, PaperController and ScissorController). Here's PaperController, as an example.

public class PaperController implements ThingOperations {
    ...
    @Override
    @RequestMapping(value="/processAddPaper", method=RequestMethod.POST)
    public String processAddThing(@Valid Paper newPaper, BindingResult result){  
       ...
    }
...

}

You see what the problem is: the implementation of processAddThing() is not correct in the example above. I should have used the Thing class as a model to be validated, as per the interface specs. But if I put @Valid Thing newThing, I won't be able to cast newThing as being a Paper instance, and therefore, I won't be able to call, say, the appropriate Service and DAO Hibernate implementations to create a new Paper record.

What do you think I should do, if I want to successfully implement my interface on my 3 controllers, and still apply a relevant @Valid annotation?

Was it helpful?

Solution

You could use generics here:

public interface ThingOperations<T extends Thing> {
    public String addThingForm();
    public String processAddThing(T thing, BindingResult result);
   ...
}

then

public class PaperController implements ThingOperations<Paper> {
    ...
    @Override
    @RequestMapping(value="/processAddPaper", method=RequestMethod.POST)
    public String processAddThing(@Valid Paper newPaper, BindingResult result){
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top