The use of Java reflection technology

Source: Internet
Author: User

Objective

When developing HTML to use jquery to submit a post, you can use jquery to iterate through the input elements of the from element to implement the parameter combination, so that you don't have to manually hit parameters, especially when the parameters are many, the effort takes time.

When I developed the Android submission HTTP request, often also submits a lot of parameters, and the parameters of which are obtained from the relevant Pojo class instances, before always using hand to hit parameters, very troublesome, the back of the thought of writing C # when used to reflect, Java should also have it, with reflection, traverse the properties of the instance class , it is much easier to return a list of parameters.

Principle

Simply record it.

User.class.getFields (): Gets all of the common (public) fields of a class, including the fields in the parent class.
User.class.getDeclaredFields (): Gets all the declared fields of a class, that is, public, private, and proteced, but does not include the declaration field of the parent class.

Field.getname () Gets the name of the field

Field.gettype () Gets the claim type of the field

GetClass (). GetName () Get the full package name and class name

Class.forName ("Reflect.demo"); Instantiate class object

Class.forName ("Reflect.person"). newinstance (); instantiate objects of other classes through class

Class.forName ("Reflect.person"). GetConstructors (); Get all the constructors

Class.forName ("Reflect.person"). Getinterfaces (); Returns the interface implemented by a class

Class.forName ("Reflect.person"). Getsuperclass (); Get the parent class in the other class

GetModifiers () Get modifier

Getparametertypes () get parameter type

Method Method=class.forname ("Reflect.person"). GetMethod ("Saychina");//Call the Saychina method in the person class
Method.invoke (Class.forName ("Reflect.person"). newinstance ());

Calling the Get,set method

    /**     * @paramobj * Action Object *@paramATT * Properties of operations **/     Public Static voidGetter (Object obj, String att) {Try{Method Method= Obj.getclass (). GetMethod ("get" +att);        System.out.println (Method.invoke (obj)); } Catch(Exception e) {e.printstacktrace (); }    }     /**     * @paramobj * Action Object *@paramATT * Properties of operations *@paramvalue * Values set by *@paramthe properties of the type * parameter **/     Public Static voidSetter (Object obj, String att, object value, Class<?>type) {        Try{Method Method= Obj.getclass (). GetMethod ("set" +att, type);        Method.invoke (obj, value); } Catch(Exception e) {e.printstacktrace (); }    }

Manipulating properties by reflection

        NULL ;         NULL ;          = Class.forName ("Reflect.person");         = demo.newinstance ();          = Demo.getdeclaredfield ("Sex");        Field.setaccessible (true);        " Male ");

Obtaining and modifying the information of an array by reflection

        int [] temp={1,2,3,4,5};        Class<?>demo=temp.getclass (). Getcomponenttype ();        System.out.println ("Array type:" +demo.getname ());        System.out.println ("Array length  " +array.getlength (temp));        System.out.println ("The first element of the array:" +array.get (temp, 0))        ; 0);        System.out.println ("The first element of a modified array is:" +array.get (temp, 0));
Realize

Understanding the principle, it is simple to realize.

/*** Get upload parameters by reflection * *@return     */     Public Staticrequestparams getparams (Object obj) {if(obj = =NULL)            return NULL; Field[] Fields=Obj.getclass (). Getdeclaredfields (); Requestparams RP=NewRequestparams ();  for(intj = 0; J < Fields.length; J + +) {fields[j].setaccessible (true); Try {                if(Fields[j].get (obj) = =NULL)                    Continue; ElseRp.add (Fields[j].getname (), string.valueof (Fields[j].get (obj))); } Catch(illegalaccessexception e) {//TODO auto-generated Catch blockE.printstacktrace (); } Catch(IllegalArgumentException e) {//TODO auto-generated Catch blockE.printstacktrace (); }        }        returnRP; }

There is one more thing we need to note about field: When the field modifier is private, we need to add

Field.setaccessible (TRUE);

Reference:

http://blog.csdn.net/z_l_l_m/article/details/8217007

Http://www.cnblogs.com/rollenholt/archive/2011/09/02/2163758.html

The use of Java reflection technology

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.