"Java EE Learning 23rd Day" "log4j use" "Ant use" "Introspection"

Source: Internet
Author: User

First, ant:http://ant.apache.org/bindownload.cgi

Second, log4j:http://logging.apache.org/log4j/2.x/download.html

Iii. Introspection

1. What is introspection.

   essentially reflection , the technology is provided by Sun, which is integrated into the JDK, and can be described as a description of the field based on the field name (String) and bytecode object: PropertyDescriptor, which gets the field's get, set method ( Method).

The JavaBean that will be used

1  PackageCom.kdyzm.domain;2 3 Importjava.util.Date;4 5  Public classPerson {6     PrivateString name;7     PrivateInteger age;8     Privatedate date;9     Ten      PublicPerson (String name, Integer age, date date) { One          This. Name =name; A          This. Age =Age ; -          This. Date =date; -     } the      PublicString GetName () { -         returnname; -     } -      Public voidsetName (String name) { +          This. Name =name; -     } +      PublicInteger getage () { A         returnAge ; at     } -      Public voidsetage (Integer age) { -          This. Age =Age ; -     } -      PublicDate getDate () { -         returndate; in     } -      Public voidsetDate (date date) { to          This. Date =date; +     } -      PublicPerson () { the     } * @Override $      PublicString toString () {Panax Notoginseng         return"Person [name=" + name + ", age=" + Age + ", date=" + Date + "]"; -     } the}

 2. Core Categories:

    (1) PropertyDescriptor class.

        [1] Inheritance Relationship

Java.lang.Object

|--java.beans.featuredescriptor

|--java.beans.propertydescriptor

        [2] Construction method

Construction Method Summary

PropertyDescriptor(String propertyName, Class<?> beanClass)
Constructs a propertydescriptor for properties that conform to standard Java conventions by invoking the Getfoo and Setfoo access methods.

PropertyDescriptor(String propertyName, Class<?> beanClass, String readMethodName, String writeMethodName)
This construction method has the name of a simple property and the name of the method used to read and write the property.

PropertyDescriptor(String propertyName, Method readMethod, Method writeMethod)
This constructor takes the name of a simple property, and the method object that is used to read and write properties.

[3] core approach

 Class<?>

getPropertyType()
Gets the property's Class object.

 Method

getReadMethod()
Gets the method that should be used to read the property value.

 Method

getWriteMethod()
Gets the method that should be used to write property values.

void

setReadMethod(Method readMethod)
Sets the method that should be used to read property values.

 void

setWriteMethod(Method writeMethod)
Sets the method that should be used to write property values.

[4] examples are used.

          The SetName method and assigns a value to the person object.

 Public voidTest1 ()throwsException {person P=NewPerson (); /*//This is achieved by ordinary reflection method.                Method Method=p.getclass (). GetMethod ("SetName", String.class);                Method.invoke (P, "Zhang San");        SYSTEM.OUT.PRINTLN (P); */        //The following is done by using introspective methods. PropertyDescriptor pd=NewPropertyDescriptor ("Name", P.getclass (), "GetName", "SetName"); Method GetName=Pd.getreadmethod (); String name=(String) Getname.invoke (p);                SYSTEM.OUT.PRINTLN (name); Method SetName=Pd.getwritemethod (); Setname.invoke (P,Xiaoqiang); GetName=Pd.getreadmethod ();        System.out.println (Getname.invoke (p)); /** OUTPUT Result: * null * Xiao Qiang*/    }

       Automatic conversions of types are not possible.

 Public void throws Exception    {person        P=new person ();        PropertyDescriptor PD=new propertydescriptor ("Age", P.getclass ());        Method setage=pd.getwritemethod ();        " 12 "); // this can only pass integer type parameters, so it will be an error!          System.out.println (p);    }

    (2) BeanInfo interface: specializes in analyzing how many properties a JavaBean has and what properties

     [1] Method for obtaining an instance of the interface

static method using the Introspector (Introspection) class (Java.lang.Object): Getbeaninfo (class<?> beanclass)

|--java.bean.introspector

Static BeanInfo

Getbeaninfo (class<?> Beanclass)
Introspect on a Java Bean to understand all of its properties, exposed methods, and events.

      [2] Core method: Getpropertygetdescriptors method.

Propertydescriptor[]

getpropertydescriptors ()
Get Beans PropertyDescriptor.

      [3] method of use.

/** Testing a very bad class: The BeanInfo class, which does not parse all the properties of a bean object successfully, but is parsed as long as the * get or set method will.     * So even the GetClass method this class will parse it as a class attribute.     * If not right, it will be resolved. */@Test Public voidTest3 ()throwsException {BeanInfo BeanInfo=introspector.getbeaninfo (person.class); PropertyDescriptor pd[]=beaninfo.getpropertydescriptors ();  for(inti=0;i<pd.length;i++) {String name=Pd[i].getname ();        SYSTEM.OUT.PRINTLN (name); }    }    

  3. Workaround for type mismatch: traverse judgment

    (1) Scene: The person class has an age member variable, an int type, and if you want to pass a string to it, you will normally get an error: mismatched parameter types. How can we solve this problem? The parameter types that can be accepted by the set method are judged, and the integer parameter is passed.

    (2) manual traverse resolution.

/** How to implement to pass a string to the Setage method * Iterate through the Set method in a convenient way * The JavaBean here must be of type Integer, otherwise not recognized. * So troublesome work Apache has developed its simplified third-party jar package: Beanutils.jar*/@Test Public voidTest4 ()throwsException, IllegalArgumentException, Illegalaccessexception, invocationtargetexception {String name= "Xiao Qiang"; String Age= "30"; Person P=NewPerson (); Method methods[]=P.getclass (). Getdeclaredmethods ();  for(Method method:methods) {String methodname=Method.getname (); //if the Set method is the next step, the Get method skips directly            if(Methodname.startswith ("Set") ) {Class<?> clazz[]=method.getparametertypes (); System.out.println (clazz[0]); if(Clazz[0].equals (String.class) {method.invoke (p,name); }                Else if(Clazz[0].equals (Integer.class) {Method.invoke (P, integer.parseint (age)); }            }            Else                Continue;    } System.out.println (P); }

  4. Using third-party jar packages: beanutils.jar resolves issues in 3 and the benefits of using third-party jar packages.

  Beanutils.jar: http://commons.apache.org/proper/commons-beanutils/download_beanutils.cgi

  Dependent Packages: Commons-logging.jar Bag

    (1) What is Beanutils.jar used for?

is a toolkit for handling javabean, and internal introspection is used, but introspection is enhanced.

    (2) What are the benefits of using the toolkit?

The Get and set methods in JavaBean no longer appear in pairs.

The ability to automate conversions of basic data types (not the basic data types cannot be converted automatically).

    (3) The demo uses the Beanutils setting value.

// Demo setting values using Beanutils     @Test    publicvoidthrows  Exception, Exception    {person        P =new person ();        Beanutils.setproperty (P,"name", "Xiao Qiang")        ; Age "," a ");         New Date ());        SYSTEM.OUT.PRINTLN (P);    }

    (4) The demo uses Beanutils to get the value.

// demonstrates using Beanutils to get a value.      @Test    publicvoidthrows  illegalaccessexception, InvocationTargetException, nosuchmethodexception    {person        p=new person ("Xiao Qiang",new  Date ());        " Name "));        " Age "));         Date "));    

    (5) Use Beanutils to encapsulate the acquired value into the JavaBean at once.

//method of filling all values once with Benutils@Test Public voidSetvalueall ()throwsException, invocationtargetexception {person P=NewPerson (); Map<string,object>map=NewHashmap<string,object>(); Map.put ("Name", "Xiao Qiang"); Map.put ("Age", "24"); Map.put ("Date",NewDate ());            Beanutils.populate (P, map); //that's the key .System.out.println (P); //This approach is widely used when analyzing the data submitted by a form and encapsulating it as JavaBean, because it can save a lot of code and be aware of the Getparametermap () method of the Request object. }

"Java EE Learning 23rd Day" "log4j use" "Ant use" "Introspection"

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.