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)

<dependency>
  <groupId>commons-beanutils</groupId>
  <artifactId>commons-beanutils</artifactId>
  <version>1.8.3</version>
</dependency>

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<String, Object> 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("<tr>");
for(String prop : props) {
  if(prop.equals("class")) continue; // we don't need the class name
  sb.append("<th>" + prop + "</th>");
}
sb.append("</tr>");

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

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 :).

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s