Java introspection instance parsing, java introspection instance

Source: Internet
Author: User

Java introspection instance parsing, java introspection instance

The number of outlines in the image. The size of the vector represents the number of vertices on the contour. Learn about JavaBean

The corresponding English word IntroSpector is used to operate JavaBean. JavaBean is a special Java class. Some of the methods comply with certain naming rules, if some methods in a Java class comply with certain naming rules, they can be used as JavaBeans.

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. This type of instance object of 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.

For example:

SetId () attribute name --> id

Attribute name of isLast () --> last

What is the property name of setCPU? --> CPU

What is the property name of getUPS? --> UPS

In short, when a class is used as a javaBean, the attributes of the JavaBean are inferred based on the method name, and it cannot 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! Benefits:

Java Beans are often used in Java EE development. 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.

Simple intranet operations on JavaBean

The java. beans. PropertyDescriptor Class is used to obtain a JavaBean attribute in a Class Object attribute set. Then, the getReadMethod () and getWriteMethod () methods are called to obtain the corresponding get and set methods.

Sample Code:

Domain class:

[Cpp] viewplaincopy

Intmain ()

package ustc.lichunchun.bean;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;}@Override   public int hashCode() {final int prime = 31;int result = 1;result = prime * result + x;result = prime * result + y;return result;}@Override   public 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;}@Override   public 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;}}

Simple introspection operations:

package ustc.lichunchun.bean;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;public class IntroSpectorTest {public static void main(String[] args) throws Exception {ReflectPoint pt1 = new ReflectPoint(3, 5);String propertyName = "x";//"x"-->"X"-->"getX"-->MethodGetX--> getProperty(pt1, propertyName);Object value = 7;setProperty(pt1, propertyName, value);System.out.println(pt1.getX());}private static void setProperty(Object pt1, String propertyName, Object value)       throws IntrospectionException, IllegalAccessException, InvocationTargetException {PropertyDescriptor pd = new PropertyDescriptor(propertyName, pt1.getClass());Method methodSetX = pd.getWriteMethod();methodSetX.invoke(pt1, value);}private static Object getProperty(Object pt1, String propertyName)       throws IntrospectionException, IllegalAccessException, InvocationTargetException {PropertyDescriptor pd = new PropertyDescriptor(propertyName, pt1.getClass());Method methodGetX = pd.getReadMethod();methodGetX.invoke(pt1);}}

Complex introspection operations on JavaBean

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.

Complex introspection operations:

package ustc.lichunchun.bean;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;public class IntroSpectorTest {public static void main(String[] args) throws Exception {ReflectPoint pt1 = new ReflectPoint(3, 5);String propertyName = "x";//"x"-->"X"-->"getX"-->MethodGetX--> Object retVal = getProperty(pt1, propertyName);System.out.println(retVal);Object value = 7;setProperty(pt1, propertyName, value);System.out.println(pt1.getX());}private static void setProperty(Object pt1, String propertyName, Object value)       throws IntrospectionException, IllegalAccessException, InvocationTargetException {PropertyDescriptor pd = new PropertyDescriptor(propertyName, pt1.getClass());Method methodSetX = pd.getWriteMethod();methodSetX.invoke(pt1, value);}private static Object getProperty(Object pt1, String propertyName)       throws IntrospectionException, IllegalAccessException, InvocationTargetException {/*     PropertyDescriptor pd = new PropertyDescriptor(propertyName, pt1.getClass());     Method methodGetX = pd.getReadMethod();     methodGetX.invoke(pt1);     */BeanInfo beanInfo = Introspector.getBeanInfo(pt1.getClass());PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();Object retVal = null;for (PropertyDescriptor pd : pds){if(pd.getName().equals(propertyName)){Method methodGetX = pd.getReadMethod();retVal = methodGetX.invoke(pt1);break;}}return retVal;}}

Use BeanUtils toolkit to operate JavaBean

Based on the preceding example, use the BeanUtils class to get the previously set attribute and then set it to a new value. The result returned by the get attribute is a string, and the set attribute can accept any type of objects. A string is usually used.

Use the PropertyUtils class to first get the previously set attribute and then set it as a new value. The result returned by the get attribute is the original type of the property, and the set attribute only accepts the original type of the property.

Note: Before using these two classes, you need to import the commons-beanutils.jar, commons-logging-1.1.jar, two jar packages in the lib folder of the eclipse project, and AddtoBuildPath.

Sample Code:

Package ustc. lichunchun. bean; 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 org. apache. commons. beanutils. beanUtils; import org. apache. commons. beanutils. propertyUtils; public class IntroSpectorTest {public static void main (String [] args) throws Exception {ReflectPoint pt1 = new ReflectPoint (3, 5); String propertyName = "x "; // "x" --> "X" --> "getX" --> MethodGetX --> Object retVal = getProperty (pt1, propertyName); System. out. println (retVal); Object value = 7; setProperty (pt1, propertyName, value); System. out. println (BeanUtils. getProperty (pt1, "x "). getClass (). getName (); // String BeanUtils. setProperty (pt1, "x", "9"); System. out. println (pt1.getX ();/* Map map = {name: "zxx", age: 18}; // BeanUtils, a new feature of Java 7. setProperty (map, "name", "kp"); */BeanUtils. setProperty (pt1, "birthday. time "," 111 "); // supports the attribute chain System. out. println (BeanUtils. getProperty (pt1, "birthday. time "); PropertyUtils. setProperty (pt1, "x", 23); System. out. println (PropertyUtils. getProperty (pt1, "x "). getClass (). getName (); // Integer/* difference between BeanUtils and PropertyUtils: BeanUtils performs operations on JavaBean in the form of strings or Map classes, in addition, the JavaBean and Map can be converted to each other (describe, populate) PropertyUtils to operate on the Data Type of the JavaBean attribute itself */} private static void setProperty (Object pt1, String propertyName, object value) throws IntrospectionException, IllegalAccessException, InvocationTargetException {PropertyDescriptor pd = new PropertyDescriptor (propertyName, pt1.getClass (); Method methodSetX = pd. getWriteMethod (); methodSetX. invoke (pt1, value);} private static Object getProperty (Object pt1, String propertyName) throws IntrospectionException, IllegalAccessException, InvocationTargetException {/* PropertyDescriptor pd = new PropertyDescriptor (propertyName, pt1.getClass (); Method methodGetX = pd. getReadMethod (); methodGetX. invoke (pt1); */BeanInfo beanInfo = Introspector. getBeanInfo (pt1.getClass (); PropertyDescriptor [] PPS = beanInfo. getPropertyDescriptors (); Object retVal = null; for (PropertyDescriptor pd: pds) {if (pd. getName (). equals (propertyName) {Method methodGetX = pd. getReadMethod (); retVal = methodGetX. invoke (pt1); break;} return retVal ;}}

Summary

The above is all the content about Java introspection instance parsing. I hope it will be helpful to you. If you are interested, you can continue to refer to other related topics on this site. If you have any shortcomings, please leave a message. Thank you for your support!

Related Article

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.