Java反射依據分歧辦法名靜態挪用分歧的辦法(實例)。本站提示廣大學習愛好者:(Java反射依據分歧辦法名靜態挪用分歧的辦法(實例))文章只能為提供參考,不一定能成為您想要的結果。以下是Java反射依據分歧辦法名靜態挪用分歧的辦法(實例)正文
list頁面的字段請求可以依據用戶的愛好停止排序,所以每一個用戶的字段都對應著分歧的次序(字段次序存數據庫),我們從數據庫裡掏出來的值是對象,然則前台傳值是用的ajax和json array,所以就面對著一個對象到json的轉換成績:1. 每一個用戶的字段次序不固定,代碼不克不及寫逝世, 2. 依據用戶字段次序去取值,假如用if斷定每一個值然後挪用分歧的辦法,if前提語句太多。然後就看了下反射。
Model 類,跟正常model一樣
public class Person { private String name; private int age; private String address; private String phoneNumber; private String sex; public String getName() { return name; } // 以下是get 和set辦法,省略。 }
測試類
import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; public class Test { // init person object. private Person initPerson() { Person p = new Person(); p.setName("name"); p.setAge(21); p.setAddress("this is my addrss"); p.setPhoneNumber("12312312312"); p.setSex("f"); return p; } public static void main(String[] args) throws SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException { Test test = new Test(); Person p = test.initPerson(); List<String> list = new ArrayList<String>(); // Add all get method. // There is no ‘()' of methods name. list.add("getName"); list.add("getAge"); list.add("getAddress"); list.add("getPhoneNumber"); list.add("getSex"); for (String str : list) { // Get method instance. first param is method name and second param is param type. // Because Java exits the same method of different params, only method name and param type can confirm a method. Method method = p.getClass().getMethod(str, new Class[0]); // First param of invoke method is the object who calls this method. // Second param is the param. System.out.println(str + "(): Get Value is " + method.invoke(p, new Object[0])); } } }
樣便可以依據數據庫獲得的字段遍歷從對象去取響應的值了
下面誰人辦法是要給list添加get辦法名,能力依據響應的get辦法名去獲得值,假如前台傳過去的只是一個屬性名,那我們還要轉換成響應的get辦法,費事。
public static void getValueByProperty(Person p, String propertyName) throws IntrospectionException, IllegalArgumentException, IllegalAccessException, InvocationTargetException { // get property by the argument propertyName. PropertyDescriptor pd = new PropertyDescriptor(propertyName, p.getClass()); Method method = pd.getReadMethod(); Object o = method.invoke(p); System.out.println("propertyName: " + propertyName + "\t value is: " + o); } public static void main(String[] args) throws SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException, IntrospectionException { Test test = new Test(); Person p = test.initPerson(); // get all properties. Field[] fields = p.getClass().getDeclaredFields(); for (Field field : fields) { getValueByProperty(p, field.getName()); } }
如許就可以直接經由過程傳過去的propertyName獲得對應的value值了
以上這篇Java反射依據分歧辦法名靜態挪用分歧的辦法(實例)就是小編分享給年夜家的全體內容了,願望能給年夜家一個參考,也願望年夜家多多支撐。