Dynamically creating a JSF form with java reflection

Viewed 1915

I'm trying to create a simple crud form to insert data into a database with hibernate, without knowing what the object type is. The ultimate goal is to only have one insert form for every table in the database. So far i get the methods that the current object has, check to see if it has any set methods and create a text input for every field that has a set.

UIViewRoot viewRoot = FacesContext.getCurrentInstance().getViewRoot();
HtmlPanelGrid hpg = (HtmlPanelGrid) viewRoot.findComponent("panel");
    for (Method method : declaredFields) {
        String name = method.getName();

        if (name.contains("set")) {
            HtmlOutputText hot = new HtmlOutputText();
            HtmlInputText hit = new HtmlInputText();
            hot.setValue(name.substring(3));
            try {
                hit.setValue(newObject.getClass().getMethod(name, String.class));
            } catch (Exception ex) {
                Logger.getLogger(ReflectController.class.getName()).log(Level.SEVERE, null, ex);
            }
            hpg.getChildren().add(hot);
            hpg.getChildren().add(hit);
        }

    }

Here newObject is the object that is going to be inserted into the database later with hibernate. My problem is this:

How do assign a certain field from that object to the text input that is being created at the moment. So far if I put the method in the value like I'm doing above, it will just print out the method in the value attribute for that input. what i want is that when this form is submited, for to assign the value in that text box to the property with that name.

3 Answers
Related