使用Java反射调用Getter和Setter

时间:2020-01-09 10:35:19  来源:igfitidea点击:

在本文中,我们将介绍如何在Java中使用反射来调用getter和setter。为了调用类的get()和set()方法,Java中有两种方法。

1.使用PropertyDescriptor类。
2.搜索该类的get和set方法并调用它。

使用PropertyDescriptor类

在PropertyDescriptor类中,有一些构造函数,我们可以在其中传递要为其创建描述符的属性,然后可以调用

  • getReadMethod()–调用getter读取属性值。
  • getWriteMethod()–调用设置器以写入属性值。

这是显示如何使用PropertyDescriptor类调用getter和setter的示例。这里有一个User类,其中包含三个字段,我们将使用PropertyDescriptor分别称为这些getter和setter。

public class User {
  private String name;
  private int age;
  boolean activeFlag;
  public String getName() {
    return name;
  }
  public void setName(String name) {
    this.name = name;
  }
  public int getAge() {
    return age;
  }
  public void setAge(int age) {
    this.age = age;
  }
  public boolean isActiveFlag() {
    return activeFlag;
  }
  public void setActiveFlag(boolean activeFlag) {
    this.activeFlag = activeFlag;
  }
}

主类具有调用User bean类的getter和setter的逻辑。

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;

public class GetterAndSetterDemo {

  public static void main(String[] args) {
    GetterAndSetterDemo gs = new GetterAndSetterDemo();
    User user = new User();
    gs.invokeSetter(user, "name", "Hercule");
    gs.invokeSetter(user, "age", 67);
    gs.invokeSetter(user, "activeFlag", true);
    
    gs.invokeGetter(user, "name");
    gs.invokeGetter(user, "age");
    gs.invokeGetter(user, "activeFlag");
  }

  private void invokeSetter(Object obj, String fieldName, Object value) {
    try {
      PropertyDescriptor pd = new PropertyDescriptor(fieldName, obj.getClass());
      // Call setter on specified property
      pd.getWriteMethod().invoke(obj, value);
    } catch (IntrospectionException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }

  private void invokeGetter(Object obj, String fieldName) {
    PropertyDescriptor pd;
    try {
      pd = new PropertyDescriptor(fieldName, obj.getClass());
      // Call getter on specified property
      System.out.println(pd.getDisplayName()+"- " + pd.getReadMethod().invoke(obj));
    } catch (IntrospectionException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }		
  }
}

输出:

name- Hercule
age- 67
activeFlag- true

搜索该类的get和set方法并调用它

调用getter和setter的另一种方法是获取类的所有方法的列表,然后从所有方法的列表中查找get和set方法并调用它们。

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class GetterAndSetterDemo {
  public static void main(String[] args) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
    GetterAndSetterDemo gs = new GetterAndSetterDemo();
    User user = new User();
    // Get all the methods
    Method[] methods = user.getClass().getDeclaredMethods();
    // search for setters 
    // First invoke all the setters to set values
    for(Method method : methods){
      if(isSetter(method)){
      System.out.println("Method Name- " + method.getName());
        if(method.getName().contains("Name")) {
          method.invoke(user, "Hercule");
        }
        if(method.getName().contains("Age")) {
          method.invoke(user, 62);
        }
        if(method.getName().contains("ActiveFlag")) {
          method.invoke(user, true);
        }
      }
    }
    // search for getters 
    for(Method method : methods){ 
      if(isGetter(method)){
        try {
          Object obj = method.invoke(user);
          System.out.println("Invoking "+ method.getName() + " Value returned is- " + obj);
        } catch (IllegalAccessException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        } catch (IllegalArgumentException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        } catch (InvocationTargetException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
      }
    }
  }

  private static boolean isGetter(Method method){
    // identify get methods
    if((method.getName().startsWith("get") || method.getName().startsWith("is")) 
        && method.getParameterCount() == 0 && !method.getReturnType().equals(void.class)){
      return true;
    }
    return false;    
  }
			    
  private static boolean isSetter(Method method){
    // identify set methods
    if(method.getName().startsWith("set") && method.getParameterCount() == 1 
        && method.getReturnType().equals(void.class)){
      return true;
    }
    return false;    
  }
}

输出:

Method Name- setName
set name called
Method Name- setActiveFlag
Method Name- setAge
Invoking getName Value returned is- Hercule
Invoking getAge Value returned is- 62
Invoking isActiveFlag Value returned is- true