In the general writing of the bean component, must write the setter and getter method, of course, if we already know the bean's related properties and methods, write beans is relatively simple, but too many components, repetitive writing is often boring boring. But when I need to invoke the properties of a dynamic object at some point, how do we set and get the properties of the object? Beanutils can help us to simplify the solution to this problem.
The latest version is now 1.9.
In the daily development, the following similar code should be very familiar.
Dynaactionform DAF = (dynaactionform) Form;
User user = new user ();
User.setid (daf.getstring ("id"));
User.setpassword (daf.getstring ("password"));
User.setusername (daf.getstring ("username"));
...
The passing of various properties of similar objects is very common in code, and the use of beanutils can simplify these tasks.
With beanutils words, the effect can be consulted:
Beanutils.copyproperties (user, DAF);
The code for copying objects using Apache Commons Beanutils is as follows:
Packagetest.ffm83.commons.beanutils;
Import Java.util.HashMap;
Importorg.apache.commons.beanutils.BeanUtils;
/* Object delivery via Commons Beanutils
* Note: The same property of the 2 beans that directly carry out clone replication between beans may have ref for the same object, especially if the property is a class.
* @author Fan Fangming
* */
public class Beanutilsusage {
public static void Main (string[] args) throws exception{
Easybean bean = new Easybean ();
Bean.setname ("Fan Fangming");
SYSTEM.OUT.PRINTLN ("target object name:" + beanutils.getproperty (Bean, "name"));
HashMap map = new HashMap ();
Map.put ("1", "12120000");
Map.put ("2", "12130000");
Beanutils.setproperty (Bean, "telephone", map);
Easybean dest = new Easybean ();
Beanutils.copyproperties (dest, Bean);
System.out.println ("... Target copy after name: "+ beanutils.getproperty (dest," name "));
System.out.println ("... After copying the target phone: "+ beanutils.getproperty (dest," telephone (1)));
}
}
After the run, the results are as follows:
Target object name: Fan Fangming
... Target after copy name: Fan Fangming
... Target after replication phone: 12120000
Apache Commons beanutils Introduction and use