Using Java Reflections API to map Object Elements
Overview
Java Reflection is used by Java Programs to inspect and modify the runtime behavior of applications running in the Java virtual machine. Its very powerful, and can be used to perform different operations at runtime. For example mapping object values at runtime. The Java reflection class are in package java.lang. We will implement a simple java program that uses java reflection to map fields of two different objects of different classes. The fields to be mapped are of access type private.Lets Begin
Create the first domain class named Institute1.package com.javainuse.domain; public class Institute1 { private String name; private int code; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getCode() { return code; } public void setCode(int code) { this.code = code; } }Create the second domain class named Institute2.
package com.javainuse.domain; public class Institute2 { private String name; private int code; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getCode() { return code; } public void setCode(int code) { this.code = code; } }We will now map the fields values of institution1 to institution2 as follows. We make use of Java Bean PropertyDescriptor for invoking getters and setters of fields.
package com.javainuse.service; import java.beans.IntrospectionException; import java.beans.PropertyDescriptor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import com.javainuse.domain.Institute1; import com.javainuse.domain.Institute2; public class JavaReflectionsExample { public static void main(String args[]) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, IntrospectionException { Institute1 inst1 = new Institute1(); inst1.setName("inst"); inst1.setCode(1); Institute2 inst2 = new Institute2(); Class<>?> objClass = inst2.getClass(); for (Field field : objClass.getDeclaredFields()) { // Invoke the getter method on the Institution1 object. Object objField = new PropertyDescriptor(field.getName(), Institute1.class).getReadMethod().invoke(inst1); // Invoke the setter method on the Institution2 object. new PropertyDescriptor(field.getName(), Institute2.class) .getWriteMethod().invoke(inst2, objField); } System.out.println("Name Value fetched using reflections" + inst2.getName()); System.out.println("Code Value fetched using reflections" + inst2.getCode()); } }
Download Source Code
Download it - Java ReflectionsSee Also
Difference between Spy and Mock in Mockito Difference between Mock thenCallRealMethod() and Spy in Mockito Checking the specified class contains a field matching the specified name using Java Reflections Getting Started with JMS Messaging- ActiveMQ Hello World Tutorial Getting Name of Current Method inside a method in Java Per4j tutorial: Getting started with Per4j