Using reflection to call methods of a Java class – A simple use case

We can use reflection feature of Java to invoke methods of a Java class.

Suppose we have a class Employee, with getter methods for fields – name, age sex, salary, city.

A user may want to send an array of property names to a method and based on the input array, we need to return the result as a comma separated String containing values for the properties in the given order.

Employee class:-

public class Employee {
    private String name;
    private int age;
    private String sex;
    private long salary;
    private String city;
    
    public Employee(String name, int age, String sex, long salary, String city) {
        super();
        this.name = name;
        this.age = age;
        this.sex = sex;
        this.salary = salary;
        this.city = city;
    }
    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    public String getSex() {
        return sex;
    }

    public long getSalary() {
        return salary;
    }

    public String getCity() {
        return city;
    }
}

Lets see how we can use reflection to call methods of the Employee class based on the input array of property names.

The following class contains a method getValues() which accepts an array of property names and an Employee object.
The getValues() method will read the array containing property names and will call the method, for each property, on the Employee object using reflection.

import java.lang.reflect.Method;

public class ReflectionTest {
    public String getValues(String[] props, Employee emp) {
        StringBuilder res = new StringBuilder();
        try {
            for (int i = 0; i < props.length; i++) {
                // Get the method for this property
                Method method = emp.getClass().getDeclaredMethod("get" + props[i]);
                // invoke the method and append the value to the result
                res.append(method.invoke(emp).toString());
                res.append(",");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return res.substring(0, res.length() - 1);
    }

    public static void main(String[] args) {
        ReflectionTest rTest = new ReflectionTest();

        Employee e1 = new Employee("Rajesh", 29, "Male", 50000, "Delhi");

        // Get values for Name and City
        System.out.println(rTest.getValues(new String[] { "Name", "City" }, e1));

        // Get Values for Name, Age, City, Salary
        System.out.println(rTest.getValues(new String[] { "Name", "Age", "City", "Salary" }, e1));

    }
}

If we run the class ReflectionTest, we get the following output:-

Rajesh,Delhi
Rajesh,29,Delhi,50000

 

Leave a Reply

Your email address will not be published. Required fields are marked *