Java sub form with generic type

Viewed 56

I have the Form classes like this

@Data
public class Form<T> {
    private T dynamicSubForm;
    private String firstName;
    private Short age;
}
@Data
public class SubForm1 {
    private String nickname;
    ...
}
@Data
public class SubForm2 {
    private Short height;
    ...
}

and I have RestController like this

@RestController
public class MyRestController {

    @GetMapping(“/form1”)
    public ResponseEntity<String> getForm1(Form<SubForm1> form) {
        form.getDynamicSubForm().getNickname(); // Error occurs here that type of form.dynamicSubForm is "Object" instead of "SubForm1".
        return new ResponseEntity<>("Hello World!", HttpStatus.OK);
    }

    @GetMapping(“/form2”)
    public ResponseEntity<String> getForm2(Form<SubForm2> form) {
        form.getDynamicSubForm().getHeight(); // Error occurs here that type of form.dynamicSubForm is "Object" instead of "SubForm2".
        return new ResponseEntity<>("Hello World!", HttpStatus.OK);
    }

}

My question is how to instantiate the dynamicSubForm with the target generic type.

1 Answers

The reason for the problem is that Java generics will be erased at runtime. You can solve this problem by constructing methods. Provide a lunch structure and a parameter structure for the form.

public Form(){}
public Form(Form form, Class cls){
  this.dynamicSubForm = (cls) form.getDynamicSubForm;
}
Related