Java反射根據不同方法名動態調用不同的方法(執行個體)_java

來源:互聯網
上載者:User

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反射根據不同方法名動態調用不同的方法(執行個體)就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援雲棲社區。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.