Dark Horse programmer java advanced technology 1.5: introspection and BeanUtils (1.7) (Zhang Xiaoxiang)

Source: Internet
Author: User


JavaBean is a special Java class that is mainly used to transmit data information. The methods in this java class are mainly used to access private fields and the method name complies with certain naming rules. If you want to transmit multiple information between two modules, You can encapsulate the information into a JavaBean. The instance Object of this JavaBean is usually called a Value Object (VO ). This information is stored using private fields in the class. If you want to read or set the values of these fields, you need to use some corresponding methods to access them. What do you think are the best names of these methods? The attributes of JavaBean are determined based on the setter and getter methods, rather than the member variables. If the method name is setId, the Chinese meaning is Set id. As for the variable to which you store the method, do you want to use it? If the method is named getId, the Chinese meaning is to get the id. Which variable do you use? Remove the set prefix. The remaining part is the attribute name. If the second letter of the remaining part is in lower case, change the first letter of the remaining part to a smaller one. SetId () attribute name? Attribute name of idisLast? What is the property name of lastsetCPU ?? What is the attribute name of CPUgetUPS ?? In short, when a class is used as a javaBean, the attributes of the JavaBean are inferred based on the method name. It does not see the member variables inside the java class. A class conforming to the characteristics of JavaBean can be used as a normal class, but using it as a JavaBean certainly requires some additional benefits, so we can understand and apply JavaBean! The advantages are as follows: in Java EE development, JavaBean is often used. Many environments require operations in the form of JavaBean. If everyone else uses and requires such operations, you have no choice! JDK provides some APIs for operations on JavaBean, which is called introspection. If you want to use the getX method to access private x, how can this problem be solved? It is more convenient to use this api to operate JavaBean than to use a common class.
 
 


The Introspector is an Introspector word. I am not very clear about the specific meaning. In simple terms, it can be said that it is an operation on the JavaBean class,

That is, read and write the member variables of the JavaBean Class Based on the provided strings without knowing the content of the JavaBean class.

The javaBean class defines the geter and seter methods for member variables, and is named according to the plan, that is, the class is named in the form of get + variable name,

If the second letter of the variable name is lower-case, the first letter of the variable name in the method must also be lower-case. Otherwise, the variable name remains unchanged.

Beanutils is an open-source java tool developed by apache. It provides powerful support for reflection and operations on the javaBean class, java is easier to use than java to operate the javaBean class. It is more and more widely used in java development. Therefore, we need to learn beanutils.

You can go to the official website of apche to download beanutils jar package, address: http://www.apache.org/dist/commons/beanutils/binaries/

Source code: http://www.apache.org/dist/commons/beanutils/source/

In addition, you also need to use the logging log toolkit to use beanutils, which is also from the official website of apche,

Address: http://commons.apache.org/logging/download_logging.cgi



This example uses eclipse to automatically generate the setter and getter methods of the ReflectPoint class. A new PropertyDescriptor object is used to help you understand the value of the JavaBean API. You can use a piece of code to read the attributes of the JavaBean, and then use a piece of code to set the attributes of the JavaBean. This example uses eclipse to extract the code for reading and setting attributes into a method: you only need to call this method and pass an object, attribute name, and setting value to this method, it can complete the attribute modification function. We recommend that you use the "obj. getClass ()" method instead of the "class name. class" method to get BeanInfo, which makes the program more universal. Search for and set the x attribute of a RefectPoint object by traversing all BeanInfo attributes. In the program, a class is treated as a JavaBean, that is, the IntroSpector. getBeanInfo method is called, and the BeanInfo object obtained encapsulates the result information of the class as a JavaBean.

import java.util.Date;public class ReflectPoint {private Date birthday = new Date();private int x;public int y;public String str1 = "ball";public String str2 = "basketball";public String str3 = "itcast";public ReflectPoint(int x, int y) {super();this.x = x;this.y = y;}@Overridepublic int hashCode() {final int prime = 31;int result = 1;result = prime * result + x;result = prime * result + y;return result;}@Overridepublic boolean equals(Object obj) {if (this == obj)return true;if (obj == null)return false;if (getClass() != obj.getClass())return false;final ReflectPoint other = (ReflectPoint) obj;if (x != other.x)return false;if (y != other.y)return false;return true;}@Overridepublic String toString(){return str1 + ":" + str2 + ":" + str3;}public int getX() {return x;}public void setX(int x) {this.x = x;}public int getY() {return y;}public void setY(int y) {this.y = y;}public Date getBirthday() {return birthday;}public void setBirthday(Date birthday) {this.birthday = birthday;}}

Import java. beans. beanInfo; import java. beans. introspectionException; import java. beans. introspector; import java. beans. propertyDescriptor; import java. lang. reflect. invocationTargetException; import java. lang. reflect. method; import java. util. map; import org. apache. commons. beanutils. beanUtils; import org. apache. commons. beanutils. propertyUtils; public class IntroSpectorTest {/*** @ param args */public static void main (String [] args) throws Exception {// TODO Auto-generated method stubReflectPoint pt1 = new ReflectPoint (3, 5); String propertyName = "x "; // "x" --> "X" --> "getX" --> MethodGetX --> Object retVal = getProperty (pt1, propertyName); System. out. println (retVal); Object value = 7; setProperties (pt1, propertyName, value); System. out. println (BeanUtils. getProperty (pt1, "x "). getClass (). getName (); BeanUtils. setProperty (pt1, "x", "9"); System. out. println (pt1.getX ();/* Map and javabean in BeanUtils can be converted to each other. * BeanUtils is developed by a third party and used directly, the new features Map map = {name: "zxx", age: 18}; BeanUtils will be used in future work. setProperty (map, "name", "lhm"); * // BeanUtils can be used to convert the basic type. The form is filled in with a string, and the response to the browser can be intBeanUtils. setProperty (pt1, "birthday. time "," 111 "); System. out. println (BeanUtils. getProperty (pt1, "birthday. time "); // BeanUtils benefits, joint attribute application PropertyUtils. setProperty (pt1, "x", 9); // The string 9 cannot be written. The System does not convert the type to the System type. out. println (PropertyUtils. getProperty (pt1, "x "). getClass (). getName ();} private static void setProperties (Object pt1, String propertyName, Object value) throws IntrospectionException, failed, InvocationTargetException {PropertyDescriptor pd2 = new PropertyDescriptor (propertyName, pt1.getClass ()); // Method methodSetX = pd2.getWriteMethod (); // The Method for writing the attribute, setmethodSetX. invoke (pt1, value); // call the reflection execution method} private static Object getProperty (Object pt1, String propertyName) throws IntrospectionException, IllegalAccessException, invocationTargetException {/* perform operations on attributes of javabean through introspection, Which is simpler: * PropertyDescriptor pd = new PropertyDescriptor (propertyName, pt1.getClass (); Method methodGetX = pd. getReadMethod (); read attribute method Object retVal = methodGetX. invoke (pt1); */BeanInfo beanInfo = Introspector. getBeanInfo (pt1.getClass (); // the province of the second method, the province of the Operation attribute PropertyDescriptor [] PPS = beanInfo. getPropertyDescriptors (); Object retVal = null; for (PropertyDescriptor pd: pds) {if (pd. getName (). equals (propertyName) {Method methodGetX = pd. getReadMethod (); // getretVal = methodGetX. invoke (pt1); // call the reflection execution method break;} return retVal ;}}



Running result:

3
Java. lang. String
9
111
Java. lang. Integer



















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.