Five ‘s Weblog

October 24, 2007


Filed under: Programming — by powerdream5 @ 10:53 pm
Tags: , ,


       Today, I found a userful utility classes package when I read my former notes. It is org.apache.commons.beanutils, one of the packages of Jakarta commons. We call the org.apache.commons.beanutils package Bean Introspection Utilities. When we use setter to initialize the properties of a Javabean, especially which has a lot of properties, we always complain that there are many setter methods needed to write. Fortunately, with the help of the org.apache.commons.beanutils, we can just use one sentence to realize that. The following is an example: (you need to download the package firstly)

// a simple javabean
public class User{
        private String username;
        private String password;
        private int age;

        //the setter, getter methods
        public String getUsername(){
               return username;
        public void setUsername(String username){
              this.username = username;
       …omit to save space …

import java.util.HashMap;
//import the necessary class
import org.apache.commons.beanutils.BeanUtils;

public class Test{
      public static void main(String[] args){

              //in order to show this example, I create a map
             //if this class is a servelet, we can use request.getParameterMap()
             //get all the properties of the form stored in a map

             HashMap map = new HashMap();
            User user = new User();
            }catch(Exception e){


       populate(java.lang.object bean, java.util.Map properties) is a static method. This method can do some basic type conversions such as from String to int. However, if there are a mismatch with the type, and cannot be converted, an exception will be thrown.


       Using this package relly makes things easy. However, some people point that the performance of this package is not good, whichis not as good as using the setter method directly. In fact, we can find the factors which influence the performance. The org.apache.commons.beanutils package is based on the mechanism of reflection. Therefore, before we can assign value to the properties, we have to introspect the bean class to find proper properties, then invoke the setter methods. Compared with using setter methods directly, this method really take a detour. However, if you don’t care a little loss in the performance of your application, and want to save some effort, using this package does no harm!


Blog at