So I have a bean that contains a list of forms that I am trying to submit using spring MVC and then each form object contains a custom property which is further extended by 2 further custom objects. The whole hierarchy is given below to keep things clear.
Class Wrapper
{
List<FormObject> formObjects;
}
Class FormObject
{
Traveller traveller;
String type;
// ( stores "Passenger" or "Vehicle" )
}
Class Passenger extends Traveller
{
}
Class Vehicle extends Traveller
{
}
In my Get Request, I have added the below model attribute
wrapper.setFormObjects(list);
//above list contains either instances of Passenger class or it contains instance of Vehicle class
model.addAttribute("wrapper", wrapper);
And the view is working perfectly fine as I am getting the list of FormObjects from this model attribute and iterating over the list of formObejcts and displaying them wherever I want them as per the requirement.
However on form submission which looks like as mentioned below
<form:form id="form_id" modelAttribute="wrapper" action="${submitUrl}" method="POST">
// other relative code
</form>
@RequestMapping(method = RequestMethod.POST)
public String saveNewTravellerDetails( @Valid @ModelAttribute("wrapper")Wrapper wrapper, final BindingResult bindingResult, final Model model, final RedirectAttributes redirectModel, final HttpServletRequest request, final HttpServletResponse response)
{
List<FormObject> formObjects = wrapper.getFormObjects();
for(FormObject object : formObjects)
{
if("passenger".equals(object.getType()))
{
// ClassCastException here
Passenger passenger = (Passenger)object.getTraveller();
}
// and here
Vehicle vehicle = (Vehicle)object.getTraveller();
}
}
Any idea How I can resolve this issue? your help will be highly appreciated.