Java reflection dynamically invokes different methods (instances) based on different method names _java

Source: Internet
Author: User
Tags reflection

The field requirements of the list page can be sorted according to the user's preference, so each user's field corresponds to a different order (the field order is stored in the database), we take out the value from the database is the object, but the foreground value is used Ajax and JSON array, So there's an object to JSON conversion problem: 1. Each user's field order is not fixed, the code can not be written dead, 2. Values are based on the order of the user's fields, and if you judge each value with if and then call a different method, the IF condition statement is too many. Then I looked at the reflection.

Model class, like normal model

public class Person {

  private String name;
  private int age;
  Private String address;
  Private String PhoneNumber;
  Private String sex;


  Public String GetName () {return
    name;
  }
The following are the get and set methods, omitted.
}


Test class

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 are My Addrss");
    P.setphonenumber ("12312312312");

    P.setsex ("F");
  return p; public static void Main (string[] args) throws SecurityException, Nosuchmethodexception, IllegalArgumentException, I
    Llegalaccessexception, invocationtargetexception {test test = new test ();
    Person P = Test.initperson ();

    list<string> list = new arraylist<string> ();

    Add all get method.

    There is no ' () ' methods name.
    List.add ("GetName");
    List.add ("Getage");
    List.add ("getaddress");
    List.add ("Getphonenumber");
    
    List.add ("Getsex"); for (String str:list) {//Get method instance. A-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]);

  The 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));


 }
  }
}

Sample can be used to retrieve the corresponding values from the object based on the fields retrieved from the database.

The above method is to add a Get method name to the list, to the corresponding get method name to obtain the value, if the foreground is passing only a property name, then we have to convert to the corresponding get method, trouble.

 public static void Getvaluebyproperty (person P, String PropertyName) throws Introspectione Xception, IllegalArgumentException, illegalaccessexception, invocationtargetexception {//Get property by the Argumen
    T 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, I
    Llegalaccessexception, 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 ()); } 
  }


So we can get the value of the PropertyName directly through the pass.

Above this Java reflection according to different method name dynamic invocation different method (instance) is small series share to everybody's content, hope can give everybody a reference, also hope everybody support cloud habitat community.

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.