August 3, 2022

Invoke Getters and Setters Using Java Reflection

In this post we’ll see how to invoke getters and setters using reflection in Java. For calling get() and set() methods of a class there are two ways in Java.

  1. Using PropertyDescriptor class.
  2. Search for get and set methods of the class and call it.

Using PropertyDescriptor class

In PropertyDescriptor class there are constructors where you can pass the property for which you want to create descriptor and then you can call-

  • getReadMethod()- To call the getter to read the property value.
  • getWriteMethod()- To call the setter to write the property value.

Here is an example to show how to use PropertyDescriptor class to invoke getters and setters. There is a User class with three fields and we’ll call these getters and setters using PropertyDescriptor.

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;
  }
}

Main class that has the logic to call getters and setters of the User bean class.

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();
    }		
  }
}
Output
name- Hercule
age- 67
activeFlag- true

Search for get and set methods of the class and call it

Another way to call getters and setters is to get the list of all the methods of the class then look for the get and set method from the list of all the methods and invoke them.

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;    
  }
}
Output
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

That's all for the topic Invoke Getters and Setters Using Java Reflection. If something is missing or you have something to share about the topic please write a comment.


You may also like

No comments:

Post a Comment