Several Methods for encapsulating javaBean

Source: Internet
Author: User

Several Methods for encapsulating javaBean

During framework development, java object (javaBean) attributes are often used to encapsulate program data. There are many methods to encapsulate javaBean, such as reflection, introspection, and tool class. Next we will start with reflection.

1. javaBean Introduction:
JavaBean is a reusable component developed using the Java language. In development, You Can Use JavaBean to reduce repeated code, making the development of the entire code more concise.

Writing requirements:
JavaBean itself is a class. When designing this class, follow these steps:

1. if the member variable name is xxx, there are two methods to get the member variable value and set the variable value. They are getXxx () and setXxx () and public: public datatype getXxx (); public void setXxx (datatype data); (2) if the member variable is boolean data, use "is" instead of "get";: public boolean isXxx (); (3) A constructor without parameters is required.
Example of a javaBean:
// JavaBeanpublic class Person {private int id; private String name; public Person (int id, String name) {super (); this. id = id; this. name = name ;}// No parameter constructor public Person () {}// obtain the Id attribute public int getId () {return id ;} // set public void setId (int id) {this. id = id;} // get method public String getName () {return name;} public void setName (String name) {this. name = name;} // tostring is not required; @ Override public String toString () {return id: + this. id + name: + this. name ;}}
2. Use reflection to encapsulate JavaBean:

You can use reflection to change the object domain to encapsulate the JavaBean. You can use the getDeclaredField method to obtain the corresponding domain and call the set Method to modify it.
The following method uses the configuration file to change the attributes of JavaBean:

The configuration file content is as follows: obj.txt com. rlovep. bean. personid = 22 name = peace code and comments: public class CofigRef {public static void main (String [] args) {try {// get the modified object; person p = (Person) getInstance (); System. out. println (p);} catch (Exception e) {// TODO Auto-generated catch block e. printStackTrace () ;}/// generate an object based on the content of the configuration file and encapsulate the attribute values of the object into the object. Public static Object getInstance () throws Exception {// input through the response stream; BufferedReader bufferedReader = new BufferedReader (new FileReader(obj.txt); String className = bufferedReader. readLine (); // read the configuration file to obtain the complete class name. Class clazz = Class. forName (className); // obtain the Constructor constructor = clazz without parameters through the class object. getConstructor (null); // create Object o = constructor. newInstance (null); // read the attribute value String line = null; while (line = bufferedReader. readLine ())! = Null) {String [] datas = line. split (=); // obtain the corresponding Field object through the attribute name. Field field = clazz. getDeclaredField (datas [0]); field. setAccessible (true); if (field. getType () = int. class) {// modify the attribute content; field. set (o, Integer. parseInt (datas [1]);} else {field. set (o, datas [1]) ;}} bufferedReader. close (); return o ;}

Using Reflection to change the value of the implemented domain is troublesome. It requires various judgments and operations and is not suitable for development.

3. Package JavaBean through Province:

Introspector is a default Java-based processing method for JavaBean class attributes and events. Java JDK provides a set of APIS for accessing the getter/setter method of a certain attribute, Which is introspection.
1. PropertyDescriptor class:
Attribute descriptor class, which can be used to obtain the get and set methods of the corresponding attribute.
GetReadMethod () to obtain the method used to read the attribute value. getWriteMethod () to obtain the method used to write the attribute value;
The demo is as follows:

// Property descriptor PropertyDescriptor descriptor = new PropertyDescriptor (id, Person. class); // get the get or set method corresponding to the property or get the property. Method m = descriptor. getWriteMethod (); // obtain the set Method of the attribute. // Execute this method to set the property value m. invoke (p, 110); // get Method; Method readMethod = descriptor. getReadMethod (); // is the get Method System for retrieving attributes. out. println (readMethod. invoke (p, null ));
Introspector class:
You can call the Introspector. getBeanInfo (People. class) method to obtain the BeanInfo object. The modified object encapsulates all attributes of the people class.
BeanInfo has the getPropertyDescriptors () method to obtain the description of the property PropertyDescriptor []. You can traverse the returned results to operate the JavaBean method. The demo is as follows:
// Introspector internal class BeanInfo beanInfo = Introspector. getBeanInfo (Person. class); // get all attribute descriptions through BeanInfo PropertyDescriptor [] descriptors = beanInfo. getPropertyDescriptors (); // get all attribute descriptors in a class for (PropertyDescriptor p: descriptors) {// get all get methods System. out. println (p. getReadMethod (); // get method}

Through the comparison between the two classes, we can see that both the PropertyDescriptor needs to be obtained, but in different ways: the former is obtained directly by creating an object, and the latter needs to be traversed, so it is more convenient to use the PropertyDescriptor class.
Introspection encapsulation is simpler than reflection, but it is essentially a variant of reflection.

4. Using BeanUtils to encapsulate JavaBean:
Every time reflection technology is used to perform such operations, it is too troublesome. Therefore, Apache developed a simple and easy-to-use API to operate Bean attributes-BeanUtils toolkit.
Note: logging is also required for applications.
BeanUtils: Link
Logging: the link uses BeanUtils:
BeanUtils mainly solves the problem: encapsulate the attribute data of an object into an object.
The attribute values obtained from the configuration file may be of the String type. The advantage of BeanUtils is that if the attribute is of the basic data type, BeanUtils will automatically convert the data type for me. If the property is set to another reference type data, you can register a type converter.
1. method for obtaining attributes: BeanUtils. getProperty (admin, "userName ");
2. method for setting attributes: BeanUtils. setProperty (admin, "id", 001 );
3. Method for copying attributes: BeanUtils. copyProperty (admin, "usetName", "peace"); same effect as set.
4. When the attribute cannot be automatically converted, use ConvertUtils. register (new Converter () to register the Converter. The demo is as follows:
Need to introduce package: commons-logging.jar, commons-beanutils-1.8.0.jar
Attributes in Admin:
private int id;private String userName;private String pwd;private int age;private Date birth;
BeanUtils is used as follows:
Public class BeanOpr {private String name; @ Test/*** @ Title: testHello * @ Description: beanutiils copy Introduction * @ return: void * @ throws * @ author peace w_peace@163.com */public void testHello () {Admin admin = new Admin (); try {// get the property method: System. out. println (BeanUtils. getProperty (admin, userName); // copy the property BeanUtils. copyProperty (admin, usetName, peace); // similar to setting the property BeanUtils. setProperty (admin, id, 001); // copy the object Admin admin2 = new Admin (); BeanUtils. copyProperties (admin2, admin); // output two admin systems. out. println (admin); System. out. println (admin2); // map data, copied to the object Map
  
   
Map = new HashMap <> (); map. put (userName, peace2); map. put (age, 22); map. put (id, 002); map. put (pwd, 123456); // copy through Map: BeanUtils. populate (admin, map); System. out. println (admin);} catch (IllegalAccessException | InvocationTargetException e) {// TODO Auto-generated catch block e. printStackTrace ();} catch (NoSuchMethodException e) {// TODO Auto-generated catch block e. printStackTrace () ;}}/***** @ T Itle: testRegist * @ Description: converts unsupported classes. * @ Return: void * @ throws * @ author peace w_peace@163.com */@ Test public void testRegist () {// register date type converter: 1, custom mode ConvertUtils. register (new Converter () {/*** Conversion Function for date conversion. * // @ Override public Object convert (Class type, Object value) {// determines whether it is of the Date type if (type! = Date. class) return null; // determines whether it is null. if (value = null |. equals (value. toString (). trim () return null; try {// conversion method SimpleDateFormat date = new SimpleDateFormat (yyyy-mm-dd); return date. parse (value. toString ();} catch (ParseException e) {throw new RuntimeException (e) ;}}, Date. class); // run Admin admin = new Admin (); Map
   
    
Map = new HashMap <> (); map. put (userName, peace2); map. put (age, 22); map. put (id, 002); map. put (pwd, 123456); map. put (birth, new Date (2015, 10, 9); try {BeanUtils. populate (admin, map); System. out. println (admin);} catch (IllegalAccessException | InvocationTargetException e) {// TODO Auto-generated catch block e. printStackTrace () ;}@ Test/***** @ Title: testRigest2 * @ Description: use the provided date type converter * @ return: void * @ throws * @ author peace w_peace@163.com */public void testRigest2 () {ConvertUtils. register (new DateConverter (), Date. class); // run Admin admin = new Admin (); Map
    
     
Map = new HashMap <> (); map. put (userName, peace2); map. put (age, 22); map. put (id, 002); map. put (pwd, 123456); map. put (birth, new Date (2015, 10, 9); try {BeanUtils. populate (admin, map); System. out. println (admin);} catch (IllegalAccessException | InvocationTargetException e) {// TODO Auto-generated catch block e. printStackTrace ();}}}
    
   
  
5. Dbutils JDBC-specific tools can also encapsulate JavaBean:

Commons-dbutils is an open-source JDBC tool library provided by the Apache organization. It is a simple encapsulation of JDBC and has very low learning costs. In addition, using dbutils can greatly simplify the workload of jdbc coding, at the same time, the program performance will not be affected.
Download link: Link
This is just a brief introduction. The following is a complete introduction in the jdbc Tutorial:

@ Test/*** @ Title: testQueryOne * @ Description: encapsulate data using the result set object provided by the component. * @ Return: void * @ throws * @ author peace w_peace@163.com */public void testQueryOne () {String SQL = select * from admin where id = ?; // Obtain connection = JdbcUtil. getConnection (); // create Dbutils core tool class QueryRunner qr = new QueryRunner (); // query and return a single object try {// use beanhandle for encapsulation // The parameters are connected in sequence, SQL statement, result processor, location parameter // check whether your result is encapsulated in Admin admin = qr. query (connection, SQL, new BeanHandler (Admin. class), 4); System. out. println (admin);} catch (SQLException e) {// TODO Auto-generated catch block e. printStackTrace ();} finally {try {connection. close ();} catch (SQLException e) {// TODO Auto-generated catch block e. printStackTrace ();}}}

 

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.