I have this structure model for my application :
public class Garage
List<Vehicule> vehicules;
...
public abstract class Vehicule
List<Wheel> wheels
...
public class Car extends Vehicule
public class Bike extends Vehicule
...
public class Wheel
boolean damaged
And I have a form which contains a checkbox input to let him know if a wheel is damaged :
<form id="garage"
action="#"
th:action="@{/save}"
th:object="${garage}"
method="post">
<div th:each="vehicule, i : ${garage.getVehicules()}">
<ul>
<li th:each="wheel, j : ${garage.getWheels()}">
<input type="checkbox" th:field="*{{vehicules[__${i.index}__].wheels}}" th:value="${wheel}" />
<label th:for="${#ids.next('wheels')}" th:text="${wheel.value}">Label</label>
</li>
</ul>
</div>
<input type="submit" value="Submit" /> <input type="reset" value="Reset" />
</form>
What I get is this error because of abstract keyword on my vehicule class :
java.lang.InstantiationException: null
at java.base/jdk.internal.reflect.InstantiationExceptionConstructorAccessorImpl.newInstance(InstantiationExceptionConstructorAccessorImpl.java:48) ~[na:na] at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:502) ~[na:na] at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:486) ~[na:na] at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:197)
Last thing, this is not my real code but it’s to provide you the most similar context for the question.
2
Answers
Ok, as Alfred said I use DTO now.
But I found the solution for my original question with a Converter configuration class and a hidden input in the template :
What I understand is in the template the hidden field calls the converter because the controller needs to create Vehicule object from a String. It works even with abstract keyword.
It means obviously, you handled abstraction inappropriately. You can always use/create Data Transfer Objects as the middleman to handle your data to and from thymeleaf forms.