feat: Add mapper for objects with same fields

This commit is contained in:
Krrish Ghimire
2019-12-03 22:49:20 +05:45
commit 2f1475b4cd
11 changed files with 365 additions and 0 deletions

21
src/Mapper.java Normal file
View File

@@ -0,0 +1,21 @@
import java.lang.reflect.*;
public class Mapper {
public Object map(Object source, String destination) {
Object object = new Object();
try {
Class<?> aClass = Class.forName(destination);
object = aClass.getConstructor().newInstance();
Field[] sourceFields = source.getClass().getDeclaredFields();
for (Field sourceField : sourceFields) {
sourceField.setAccessible(true);
Field destinationField = object.getClass().getDeclaredField(sourceField.getName());
destinationField.setAccessible(true);
destinationField.set(object, sourceField.get(source));
}
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException | NoSuchFieldException e) {
e.printStackTrace();
}
return object;
}
}