Thursday 12 December 2019

Reflection: get value of object property


Below function return the value associated with object property.
@SuppressWarnings("unchecked")
public static <V> V get(Object object, String fieldName) {
	Class<?> clazz = object.getClass();
	while (clazz != null) {
		try {
			Field field = clazz.getDeclaredField(fieldName);
			field.setAccessible(true);
			return (V) field.get(object);
		} catch (Exception e) {
			throw new IllegalStateException(e);
		}
	}
	return null;
}

Find the below working application.

Employee.java
package com.sample.app.model;

public class Employee {
	private int id;
	private String name;

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

}


MainApp.java
package com.sample.app;

import java.lang.reflect.Field;

import com.sample.app.model.Employee;

public class MainApp {
	public static boolean set(Object object, String fieldName, Object fieldValue) {
		Class<?> clazz = object.getClass();
		while (clazz != null) {
			try {
				Field field = clazz.getDeclaredField(fieldName);
				field.setAccessible(true);
				field.set(object, fieldValue);
				return true;
			} catch (Exception e) {
				throw new IllegalStateException(e);
			}
		}
		return false;
	}

	@SuppressWarnings("unchecked")
	public static <V> V get(Object object, String fieldName) {
		Class<?> clazz = object.getClass();
		while (clazz != null) {
			try {
				Field field = clazz.getDeclaredField(fieldName);
				field.setAccessible(true);
				return (V) field.get(object);
			} catch (Exception e) {
				throw new IllegalStateException(e);
			}
		}
		return null;
	}

	public static void main(String args[]) throws InstantiationException, IllegalAccessException {
		Object object = Employee.class.newInstance();
		
		set(object, "id", 123);
		set(object, "name", "Krishna");
		
		System.out.println("id : " + get(object, "id"));
		System.out.println("name : " + get(object, "name"));
	}
}


Run MainApp.java, you will see below messages in console.
id : 123
name : Krishna





Previous                                                    Next                                                    Home

No comments:

Post a Comment