Use of the Beanutil tool class

Source: Internet
Author: User
Tags print format reflection uuid

Introduction to the use of Beanutils 1.commons-beanutils

Commons-beanutils is a basic open source library under the Apache organization, which provides packaging for Java reflection and introspection APIs, relies on introspection, and its main purpose is to use the reflection mechanism to handle the properties of JavaBean. We know that a javabean usually contains a large number of properties, in many cases, the processing of JavaBean led to a large number of Get/set code accumulation, increasing the length of code and the difficulty of reading code, now with Beanutils, Our handling of the JavaBean property is much more convenient. Use of 2.BeanUtils

Beanutils is a tool class under the Commons-beanutils package, and if you want to use this class in our project, you need to import the following two jar packages:

L Commons-beanutils.jar

L Commons-logging.jar

Here we will practice how to use beanutils, case details please refer to beanutils use case detailed, click here to download the case source code, specific as follows:

(1) Create a Web application, Example5, to web-inf/lib the two jar packages mentioned above;

(2) Under the application of the SRC directory under the new class, the name of person, the main code as shown in example 1-1:

Case 1-1 Person.java

Public class person {

Private Stringname;

private int age;

Private Stringgender;

private Boolean bool;

The Get/set method of the above four attributes is omitted here

@Override

Public String toString () {

return "Person [name=] + name +", age= "+ Age +", gender= "+ gender

+ "]";

}

}

In Example 1-1, four member variables are defined and the ToString () method is overridden.

(3) A new class class in the SRC directory, named demo, defines a unit test method in the class, and the main code is shown in example 1-2:

Case 1-2 Demo.java

Public class Demo {

@Test

Public void fun1 () throws exception{

String classname= "Cn.itcast.domain.Person";

Class Clazz=class.forname (className);

Object bean=clazz.newinstance ();

Beanutils.setproperty (Bean, "name", "John");

Beanutils.setproperty (Bean, "age", "23");

Beanutils.setproperty (Bean, "gender", "male");

Beanutils.setproperty (bean, "xxx", "xxx");

System.out.println (Bean);

}

}

In example 1-2, the object of the person class is obtained using reflection, and then the static method SetProperty (object bean,string name,object value) of the Beanutils class assigns a value to the specified property of the specified bean. The first parameter of the method is the JavaBean object, the second parameter is the JavaBean property, and the third parameter is the value of the property.

(4) Run the Demo Class unit test Method Fun1 (), the console printing results as shown in Figure 1-1:

Figure 1-1 Console Print Results

In Figure 1-1, the print format for the person information is set in the ToString () method of the person class.

(5) Use the Beanutils getproperty (Object bean,string name) method to get the specified property value of the specified bean, as shown in example 1-3:

Public class Demo {

@Test

Public void fun1 () throws exception{

String classname= "Cn.itcast.domain.Person";

Class Clazz=class.forname (className);

Object bean=clazz.newinstance ();

Beanutils.setproperty (Bean, "name", "John");

Beanutils.setproperty (Bean, "age", "23");

Beanutils.setproperty (Bean, "gender", "male");

Beanutils.setproperty (bean, "xxx", "xxx");

System.out.println (Bean);

String age = beanutils.getproperty (Beans, "age");

System.out.println (age);

}

}

(6) Test the Fun1 method, the console prints the result as shown in Figure 1-2:

Figure 1-2 Console Print Results

The above is the SetProperty () and GetProperty () method of the Beanutils class to set up and obtain the JavaBean attribute, which may be required in development: the request parameters submitted by the form are encapsulated in a javabean. The SetProperty () and GetProperty () method of beanutils will be troublesome at this time, so beanutils provides us with a static method populate (Object Bean,map properties), where the second parameter is the map that encapsulates the request parameter, we can get a map object that encapsulates all the request parameters through the Request.getparametermap () method.

Here's an example to understand the populate (Object Bean,map properties) method of the Beanutils class, as follows:

(7) Create a JavaBean class in Example5, User, the main code is shown in example 1-4:

Case 1-4 User.java

Public class User {

Private Stringusername;

Private String password;

The Get/set method for omitting the member variables of the user class here

@Override

Public String toString () {

return "User [username=" + Username + ", password=" + password + "]";

}

}

(8) Define a unit test method fun2 in the demo class, the main code is shown in example 1-5:

Example 1-5 fun2 () method

@Test

Public void fun2 () throws Exception {

map<string,string> map = new hashmap<string,string> ();

Map.put ("username", "Zhangsan");

Map.put ("password", "123");

User user = new user ();

Beanutils.populate (user, map);

SYSTEM.OUT.PRINTLN (user);

}

In example 1-5, the data inside the map is encapsulated into JavaBean, and there is a requirement that the key value in the map be consistent with the name of the property in JavaBean, otherwise it will not be encapsulated.

(9) Test the Fun2 method, the console prints the result as shown in Figure 1-3:

Figure 1-3 Console Print Results

Now we encapsulate the beanutils and encapsulate it as a tool class, and we've also encapsulated a similar tool class that provides a way to get a 32-bit-length uppercase string that is not duplicated, as follows:

(10) Create a tool class in Example5, named Commonutils, in which a method is defined to encapsulate the data in the map into JavaBean, as shown in example 1-6:

Case 1-6 Commonutils.java

Public class commonutils {

/**

* Generate a 32-bit long uppercase string with no duplicates

* @return

*/

Public Static String uuid () {

return Uuid.randomuuid (). toString (). Replace ("-", ""). toUpperCase ();

}

/**

* Converts a map to a JavaBean object of the specified type

* @param Map

* @param clazz

* @return

*/

Public static <T> T Tobean (map map, class<t> Clazz) {

Try {

/*

* 1. Create a JavaBean object of the specified type

*/

T bean = clazz.newinstance ();

/*

* 2. To encapsulate data in a JavaBean

*/

Beanutils.populate (bean, map);

/*

* Return JavaBean Object

*/

return bean;

Catch(Exception e) {

throw New RuntimeException (e);

}

}

}

In example 1-6, commonutils defines a static generic method: Tobean (Map map,class<t> clazz), based on the parameters passed to determine which JavaBean to encapsulate the data in the MAP. It uses reflection to get the JavaBean object of the specified type, and then calls the populate () method of the Beanutils class.

(11) Define a unit test method Fun3 in the demo class, the main code is shown in example 1-7:

Example 1-7 fun3 () method

@Test

Public void Fun3 () {

map<string,string> map = new hashmap<string,string> ();

Map.put ("username", "Lisi");

Map.put ("password", "123");

/*

* REQUEST.GETPARAMETERMAP ();

*/

User user = Commonutils.tobean (map, user. Class);

SYSTEM.OUT.PRINTLN (user);

}

In example 1-7, the data in the map is encapsulated into user by using the Tobean () method of the Commonutils class, and then returns a user object.

(12) To run the Fun3 () method, the console prints the result as shown in Figure 1-4:

Figure 1-4 Console Print Results

Note that exceptions are thrown when using the SetProperty (), GetProperty (), and populate () methods of the Beanutils class, and the Help class we create needs to handle the exception. This way, when you invoke this method of the helper class, you no longer have to handle the exception. Also, when you call the Beanutils setproperty () method, the method does not throw an exception if the property you set does not exist or if you do not assign a value to a property of JavaBean.

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.