skip to Main Content

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


  1. Chosen as BEST ANSWER

    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 :

    <input type="hidden" th:field="*{vehicules[__${i.index}__]}" />
    
    public class VehiculeConverter implements Converter<String, Vehicule> {
        @Override
        public Vehicule convert(String source) {
            // return Car or Bike
        }
    }
    
    @Configuration
    public class FormattersConfig implements WebMvcConfigurer {
        @Override
        public void addFormatters(FormatterRegistry registry) {
            registry.addConverter(new VehiculeConverter());
        }
    }
    

    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.


  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search