Using BeanUtils Reflection to Print HTML Table Without Hardcoding the Column

Apache Commons BeanUtils is a little (very) useful library you can use to perform metadata reflection work on the runtime. To use it with Maven, add following dependency (check http://search.maven.org for latest version)


  commons-beanutils
  commons-beanutils
  1.8.3

Supposed you have a simple domain class that represent a user with 3 properties (name, age, weight) like this

public class User {
        private String name;
        private int age;
        private int weight;
        
        /* Getters & Setters */
}

You can get all the name of the properties on the runtime simply by using describe method of BeanUtils

User u = new User();
Map props = BeanUtils.describe(u);

// Below will print [weight, name, age, class]
System.out.println(props.keySet());

Which means.. you can use BeanUtils to introspect your property names and do useful stuff .. eg: printing HTML table without even hardcoding the column

// Print headings
sb.append("");
for(String prop : props) {
  if(prop.equals("class")) continue; // we don't need the class name
  sb.append("" + prop + "");
}
sb.append("");

// Print rows
for(User u : users) {
  sb.append("");
  for(String prop : props)  {
    if(prop.equals("class")) continue; // we don't need the class name
    sb.append("" + BeanUtils.getProperty(u, prop) + "");
  }
  sb.append("");
}

And of course you have to take this further. Eg: on Spring MVC you can do similar thing: dump all the column name and values into your model object, and you can have a generic view that prints all sorts of domain object collection into a table.

How cool is that :).

Leave a Reply