0

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.

Ashish Jagga
  • 189
  • 3
  • 6
  • 10

2 Answers2

0

You cannot cast a superclass into a subclass. This is a fundamental Java concept and has nothing to do with Spring. This question is pretty common and has been answered many times. Hope this helps: explicit casting from super class to subclass

GbGbGbGbEB
  • 56
  • 1
  • 6
  • you are wrong mate! I am sure you must have missed my below comment. wrapper.setFormObjects(list); //above list contains either instances of Passenger class or it contains instance of Vehicle class And it has to do with Spring FYI :) Please have a look at this link, might help you understand the problem. http://forum.spring.io/forum/spring-projects/web/87283-problem-binding-subclasses The only difference is my problem is deeper than is mentioned in the link I just provided. – Ashish Jagga Mar 17 '18 at 18:41
0

I finally found the solution to my problem. I made it work by storing my model attribute "wrapper" in HTTP session by using @SessionAttributes annotation at the controller level.

Ashish Jagga
  • 189
  • 3
  • 6
  • 10