Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Invoke Getters And Setters Using Reflection in java

In this post, we will see how to call getters and Setters using reflection in java. We have already seen how to invoke method using reflection in java.

There are two ways to invoke getter and setter using reflection in java.


Using PropertyDescriptor

You can use PropertyDescriptor to call getters and setters using reflection.
Getter: call getReadMethod() on PropertyDescriptor
Setter: Call getWriteMethod() on PropertyDescriptor.

Let’s understand with simple example.
We will create an object of employee object and then will invoke getters and setters on that.
Create Employee.java as below.

package org.arpit.java2blog;

public class Employee {
	String name;
	int age;
	
	public Employee()
	{
		
	}
	public Employee(String name, int age) {
		this.name=name;
		this.age=age;
	}
	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;
	}
}

Create InvokeGetterSetterMain to call getters and setters on employee object.

package org.arpit.java2blog;

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

public class InvokeGetterSetterMain {
	public static void main(String[] args)
	{
		InvokeGetterSetterMain igsm=new InvokeGetterSetterMain();
		Employee emp1=new Employee();
		igsm.invokeSetter(emp1, "name", "John");
		igsm.invokeSetter(emp1, "age", 25);

		igsm.invokeGetter(emp1, "name");
		igsm.invokeGetter(emp1, "age");

	}

	public void invokeSetter(Object obj, String propertyName, Object variableValue)
	{
		PropertyDescriptor pd;
		try {
			pd = new PropertyDescriptor(propertyName, obj.getClass());
			Method setter = pd.getWriteMethod();
			try {
				setter.invoke(obj,variableValue);
			} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
				e.printStackTrace();
			}
		} catch (IntrospectionException e) {
			e.printStackTrace();
		}

	}

	public void invokeGetter(Object obj, String variableName)
	{
		try {
			PropertyDescriptor pd = new PropertyDescriptor(variableName, obj.getClass());
			Method getter = pd.getReadMethod();
			Object f = getter.invoke(obj);
			System.out.println(f);
		} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | IntrospectionException e) {
			e.printStackTrace();
		}
	}
}

When you run above program, you will get below output:

John
25

As you can see, we are able to call getters and setters using reflection.


Using Class’s getDeclaredMethods

We can search for getter and setter of any attributes and invoke it.
Here is simple program for the same.

package org.arpit.java2blog;

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

public class InvokeGetterSetterWithMethodsMain {

	public static void main(String[] args) {
		InvokeGetterSetterWithMethodsMain igsm=new InvokeGetterSetterWithMethodsMain();
		Employee emp1=new Employee();

		Method methodName= igsm.getMethod("name",emp1.getClass(),"setter");
		igsm.invokeSetter(emp1, "Martin",methodName);

		Method methodAge= igsm.getMethod("age",emp1.getClass(),"setter");
		igsm.invokeSetter(emp1, 28,methodAge);

		Method methodNameGet= igsm.getMethod("name",emp1.getClass(),"getter");
		igsm.invokeGetter(emp1,methodNameGet);
		
		Method methodAgeGet= igsm.getMethod("age",emp1.getClass(),"getter");
		igsm.invokeGetter(emp1,methodAgeGet);
	}
	public Method getMethod(String variableName,Class aClass,String getterOrSetter)
	{

		Method[] declaredMethods = aClass.getDeclaredMethods();
		for (Method method:declaredMethods) {
			if(getterOrSetter.equalsIgnoreCase("getter"))
			{
				if(isGetter(method) && method.getName().toUpperCase().contains(variableName.toUpperCase()))
				{
					return method;
				}
			}
			if(getterOrSetter.equalsIgnoreCase("setter"))
			{
				if(isSetter(method) && method.getName().toUpperCase().contains(variableName.toUpperCase()))
				{
					return method;
				}
			}
		}
		return null;
	}
	private static boolean isGetter(Method method){
		// check for getter 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){
		// check for setter methods
		if(method.getName().startsWith("set") && method.getParameterCount() == 1 
				&& method.getReturnType().equals(void.class)){
			return true;
		}
		return false;    
	}

	public void invokeSetter(Object obj,Object variableValue,Method setter)
	{
		try {
			setter.invoke(obj,variableValue);
		} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
			e.printStackTrace();
		}

	}

	public void invokeGetter(Object obj,Method getter)
	{
		try {
			Object f = getter.invoke(obj);
			System.out.println(f);
		} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
			e.printStackTrace();
		}
	}
}

When you run above program, you will get below output:

Martin
28

That’s all about how to invoke Getters And Setters Using Reflection in java

The post Invoke Getters And Setters Using Reflection in java appeared first on Java2Blog.



This post first appeared on How To Learn Java Programming, please read the originial post: here

Share the post

Invoke Getters And Setters Using Reflection in java

×

Subscribe to How To Learn Java Programming

Get updates delivered right to your inbox!

Thank you for your subscription

×