0

Suppose that we have classes:

public class BasicCustomer {
    private String name;
    private String email;
    ----getters and setters omited----
}

public class CustomerWithDog extends BasicCustomer{
    private String dogName;
    private String dogRace;
    ----getters and setters omited----
}

public class CustomerWithCat extends BasicCustomer{
    private String catName;
    private String catRace;
    ----getters and setters omited----
}

Only when customer is logged in, I can deduce which type he is.

Question: is there a way to dynamically create form with appropriate fields for specific type of customer (CustomerWithCat should see form that have inputs for name, email, catName and catRace)?

If I use java.lang.reflect.Field class to get fields from class, then I should use Field.setAccessible(true) (because fields are private) which, on the other hand violate encapsulation (and gets around getters and setters, which is not what I want).

I look at:

How to create dynamic JSF form fields

solution no.1, but I don't understand how to populate value attributes because if user is BasicCustomer then it can't reference fields from CustomerWithCat even if they are not rendered.

Community
  • 1
  • 1
Freeman
  • 232
  • 1
  • 2
  • 11
  • I would approach this by creating a `FormGenerator` class that generates the form with appropriate subclasses for each type. Then each customer type returns the appropriate generator. Or you could have a FormGeneratorFactory. – Daniel Bickler Apr 21 '17 at 14:02
  • Why do you want to dynamically create the form which will add to complexity and overhead? since you have concrete classes, you could have separate forms for each class and make the switch to or render the appropriate form conditionally based on the user type. – OTM Apr 21 '17 at 16:24
  • I suppose that it would be easier to have one form that can be customize for each user type but, obviously, I was wrong. Thanks anyway. – Freeman Apr 23 '17 at 09:08

0 Answers0