Java反射根据不同方法名动态调用不同的方法(实例)
list页面的字段要求可以根据用户的喜好进行排序,所以每个用户的字段都对应着不同的顺序(字段顺序存数据库),我们从数据库里取出来的值是对象,但是前台传值是用的ajax和jsonarray,所以就面临着一个对象到json的转换问题:1.每个用户的字段顺序不固定,代码不能写死,2.根据用户字段顺序去取值,如果用if判断每个值然后调用不同的方法,if条件语句太多。然后就看了下反射。
Model类,跟正常model一样
publicclassPerson{ privateStringname; privateintage; privateStringaddress; privateStringphoneNumber; privateStringsex; publicStringgetName(){ returnname; } //以下是get和set方法,省略。 }
importjava.lang.reflect.InvocationTargetException; importjava.lang.reflect.Method; importjava.util.ArrayList; importjava.util.List; publicclassTest{ //initpersonobject. privatePersoninitPerson(){ Personp=newPerson(); p.setName("name"); p.setAge(21); p.setAddress("thisismyaddrss"); p.setPhoneNumber("12312312312"); p.setSex("f"); returnp; } publicstaticvoidmain(String[]args)throwsSecurityException,NoSuchMethodException,IllegalArgumentException,IllegalAccessException,InvocationTargetException{ Testtest=newTest(); Personp=test.initPerson(); List<String>list=newArrayList<String>(); //Addallgetmethod. //Thereisno‘()'ofmethodsname. list.add("getName"); list.add("getAge"); list.add("getAddress"); list.add("getPhoneNumber"); list.add("getSex"); for(Stringstr:list){ //Getmethodinstance.firstparamismethodnameandsecondparamisparamtype. //BecauseJavaexitsthesamemethodofdifferentparams,onlymethodnameandparamtypecanconfirmamethod. Methodmethod=p.getClass().getMethod(str,newClass[0]); //Firstparamofinvokemethodistheobjectwhocallsthismethod. //Secondparamistheparam. System.out.println(str+"():GetValueis"+method.invoke(p,newObject[0])); } } }
样就可以根据数据库获取的字段遍历从对象去取相应的值了
上面那个方法是要给list添加get方法名,才能根据相应的get方法名去获取值,如果前台传过来的只是一个属性名,那我们还要转换成相应的get方法,麻烦。
publicstaticvoidgetValueByProperty(Personp,StringpropertyName)throwsIntrospectionException,IllegalArgumentException,IllegalAccessException,InvocationTargetException{ //getpropertybytheargumentpropertyName. PropertyDescriptorpd=newPropertyDescriptor(propertyName,p.getClass()); Methodmethod=pd.getReadMethod(); Objecto=method.invoke(p); System.out.println("propertyName:"+propertyName+"\tvalueis:"+o); } publicstaticvoidmain(String[]args)throwsSecurityException,NoSuchMethodException,IllegalArgumentException,IllegalAccessException,InvocationTargetException,IntrospectionException{ Testtest=newTest(); Personp=test.initPerson(); //getallproperties. Field[]fields=p.getClass().getDeclaredFields(); for(Fieldfield:fields){ getValueByProperty(p,field.getName()); } }
以上这篇Java反射根据不同方法名动态调用不同的方法(实例)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。