BeanUtils-org.apache.commons.beanutils.BeanUtils

Source: Internet
Author: User
Transferred from: Http://www.blogjava.net/huanzhugege/archive/2007/02/05/97964.html Beanutils
Beanutils is another very convenient class library provided by the Apache-Commons project. Through this class library, reflection can be used more conveniently. The most common class is beanutils (in the org. Apache. commons. beanutils Package). You can use this class to access a property in a bean by name.
You can use beanutils. getproperty (person, "age") to obtain the age attribute of person. This method also supports embedded objects, such as beanutils. getproperty (person, "manager. Name"), to get the name attribute of the Manager attribute of the person. The list and map attributes are also supported. The following syntax can be used to obtain the name beanutils. getproperty (orderbean, "MERs [1]. Name") of the first customer in the order customer list "). You can use the beanutils. setproperty method to set the attribute value of JavaBean.
Constructorutils provides methods to call constructors. Using public static object invokeconstructor (class Klass, object Arg), you can directly call constructors of a class.
Methodutils provides a method to call the bean method, using methodutils. invokemethod (bean, methodname, parameter); you can directly call a method of a class.
Propertyutils provides more detailed attribute access methods. You can use public static class getpropertytype (Object bean, string name) to obtain the class type of the attribute.
Userinfo = (userinfo) constructorutils. invokeconstructor (
Userinfo. Class, new object [] {});
Personinfo = (personinfo) constructorutils
. Invokeconstructor (personinfo. Class, new object [] {});
Beanutils. setproperty (personinfo, "Age", new INTEGER (20 ));
Beanutils. setproperty (personinfo, "name", "Tom ");
Beanutils. setproperty (userinfo, "Number", "admin ");
Beanutils. setproperty (userinfo, "person", personinfo );
System. Out. println (beanutils. getproperty (userinfo, "person. Name "));
Beanutils. setproperty (userinfo, "person. Name", "XDX ");
System. Out. println (beanutils. getproperty (userinfo, "person. Name "));
System. Out. println (propertyutils. getpropertytype (userinfo, "person "));
Running result:
Tom
XDX
Class com. cownew. PIs. basedata. Common. personinfo ---------------------------------------------------------------------

Beanutils uses magic reflection technology to implement a lot of exaggerated and useful functions, which are hard to imagine in the C/C ++ era. No matter who the project is, it will always be used in a day. I have never realized it. I missed it the first time I saw it.

1. Dynamic getter and setter of attributes

In the age when the framework was full, the getter and setter functions were not always executed. Sometimes the attributes were obtained dynamically based on the name, just like this:
 
Beanutils. getproperty (mybean, "Code ");
The better feature of common beanutils is that it can directly access the attributes of embedded objects, as long as they are separated by dots.
 
Beanutils. getproperty (orderbean, "address. City ");
In contrast, beanutils of other class libraries is usually very simple and cannot access embedded objects. Therefore, you may need to replace them with commons beanutils.

Beanutils also supports list and map attributes. The following syntax can be used to obtain the name of the first customer in the order customer list.

 
Beanutils. getproperty (orderbean, "MERs [1]. Name ");
Beanutils converts the string type to the real type of the bean attribute using the convertutils class, facilitating bean extraction from objects such as httpservletrequest, or outputting the bean to the page. Propertyutils retains the original bean type.

2. beancompartor dynamic sorting

Or through reflection, we can dynamically set the attribute to which the bean is sorted, instead of implementing the bean compare interface for Complex Condition judgment.
 
List tables les =...; // list of person objects collections. Sort (Tables les, new beancomparator ("Age "));

If you want to support composite sorting of multiple attributes, such as "order by lastname, firstname"

 
Arraylist sortfields = new arraylist (); sortfields. add (New beancomparator ("lastname"); sortfields. add (New beancomparator ("firstname"); comparatorchain multisort = new comparatorchain (sortfields); collections. sort (rows, multisort );

Comparatorchain belongs to the jakata commons-collections package.
If the age attribute is not of the normal type, the constructor needs to input a comparator object to sort the age variable.
In addition, beancompartor's compareblecomparator throws an exception when its attribute is null, and cannot set the ascending or descending order. At this time, we need to use the comparatorutils of the commons-collections package.

 
Comparator mycmp = comparablecomparator. getinstance ();
Mycmp = comparatorutils. nulllowcomparator (mycmp); // allow null
Mycmp = comparatorutils. reversedcomparator (mycmp); // reverse
Comparator CMP = new beancomparator (sortcolumn, mycmp );

3. converter binds the string in the request or resultset to the attributes of the object.

It is often necessary to retrieve values from objects such as request and resultset to be assigned to the bean. If the binding function of the MVC framework is not needed, the followingCodeEveryone is tired of writing.

 
String A = request. getparameter ("A"); bean. Seta (a); string B = ....
Bean. SETB (B );
......

Write a binder to automatically bind all attributes:

Mybean bean = ...; hashmap map = new hashmap (); enumeration names = request. getparameternames (); While (names. hasmoreelements () {string name = (string) names. nextelement (); map. put (name, request. getparametervalues (name);} beanutils. populate (bean, MAP );

The beanutils populate method or getproperty and setproperty Methods call convert for conversion.
Converter only supports some basic types, and even the java. util. date type is not supported. In addition, it is stupid because an exception is thrown when you encounter a unknown type. For the date type, I have implemented a converter according to its sqldate type, and added a function to set the date format.
To register this converter, you need the following statement:

Convertutilsbean convertutils = new convertutilsbean ();
Dateconverter = new dateconverter ();
Convertutils. Register (dateconverter, date. Class );



// To register converter, you cannot use the beanutils static method. You must create a beanutilsbean instance.
Beanutilsbean beanutils = new beanutilsbean (convertutils, new propertyutilsbean ());
Beanutils. setproperty (bean, name, value );

4. Other functions

4.1 constructorutils: dynamically create objects
 
Public static object invokeconstructor (class Klass, object Arg)

4.2 methodutils, dynamic call Method

 
Methodutils. invokemethod (bean, methodname, parameter );

4.3 propertyutils: When the attribute is collection and map, it dynamically reads:
Collection: Provides Index

 
Beanutils. getindexedproperty (orderbean, "items", 1 );

Or

 
Beanutils. getindexedproperty (orderbean, "items [1]");

Map: provides key value

 
Beanutils. getmappedproperty (orderbean, "items", "111"); // key-value goods_no = 111

Or

 
Beanutils. getmappedproperty (orderbean, "items (111 )")

4.4 propertyutils: directly obtains the class type of the attribute.
 
Public static class getpropertytype (Object bean, string name)
4.5 dynamic Bean See Remove unnecessary vo and formbean with dynabean

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.