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