Dynamic invocation of the class's set and get methods through the reflection of Java

Source: Internet
Author: User

Method One:

1   Public Static voidMain (string[] args)throwsException {2Class clazz = Class.forName ("Taskprovidepropslist");//the class name here is the full name: If you have a bag, add the package name.3Object obj =clazz.newinstance (); 4field[] Fields =Clazz.getdeclaredfields (); 5   //Write Data6    for(Field f:fields) {7PropertyDescriptor PD =NewPropertyDescriptor (F.getname (), clazz); 8Method WM = Pd.getwritemethod ();//Get Write Method9Wm.invoke (obj, 2);//because you know the attribute of type int, it is just a passing int. In fact, we need to judge the type of his parameter.Ten   }   One   //Read Data A    for(Field f:fields) { -PropertyDescriptor PD =NewPropertyDescriptor (F.getname (), clazz);  -Method RM = Pd.getreadmethod ();//Get Read Method theInteger num = (integer) rm.invoke (obj);//because you know the attribute of type int, you convert it to an integer. You can also not convert direct printing - System.out.println (num);  -   }   -  }   +}
1  Public Static voidGetMethodDemo2 ()throwsException {2Class clazz = Class.forName ("Com.itcast.day26.Person");3         //Field field = Clazz.getdeclaredfield ("name");4Object obj =clazz.newinstance ();5         6PropertyDescriptor PD =NewPropertyDescriptor ("name", clazz);7Method get =Pd.getreadmethod ();8String name =(String) get.invoke (obj);9 System.out.println (name);Ten}

Method Two:

 1  public  object GetValue (Object Dto, String name) throws   exception{ 2  method[] m = Dto.getclass (). GetMethods ();  3  for  (inti=0;i<m.length;i++ 4  if (("Get" +name). toLowerCase (). Equals (M[i].getname (). toLowerCase ())) { 5  return   m[  I].invoke (DTO);  6  }  7 } 

Dynamic invocation of the class's set and get methods through the reflection of Java

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.