fix: Ignore if field does not exist

This commit is contained in:
Krrish Ghimire
2019-12-03 23:25:18 +05:45
parent 8f4f154879
commit 8fc1410cd0
5 changed files with 43 additions and 34 deletions

View File

@@ -0,0 +1,24 @@
package np.com.krrish;
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 e) {
e.printStackTrace();
} catch (NoSuchFieldException ignored) {
}
return object;
}
}