Browse Source

fix: Accept class parameter for destination instead of class name

master
Krrish Ghimire 5 years ago
parent
commit
39ef4515e4
  1. 6
      .gitignore
  2. 4
      src/np/com/krrish/Mapper.java
  3. 4
      test/np/com/krrish/MapperTest.java

6
.gitignore vendored

@ -1,3 +1,7 @@
.gradle/** .gradle/**
.idea/** .idea/**
build/** build/classes/**
build/generated/**
build/reports/**
build/test-results/**
build/tmp/**

4
src/np/com/krrish/Mapper.java

@ -3,10 +3,10 @@ package np.com.krrish;
import java.lang.reflect.*; import java.lang.reflect.*;
public class Mapper { public class Mapper {
public static Object map(Object source, String destination) { public static Object map(Object source, Class destination) {
Object object = new Object(); Object object = new Object();
try { try {
Class<?> aClass = Class.forName(destination); Class<?> aClass = Class.forName(destination.getName());
object = aClass.getConstructor().newInstance(); object = aClass.getConstructor().newInstance();
Field[] sourceFields = source.getClass().getDeclaredFields(); Field[] sourceFields = source.getClass().getDeclaredFields();
for (Field sourceField : sourceFields) { for (Field sourceField : sourceFields) {

4
test/np/com/krrish/MapperTest.java

@ -9,7 +9,7 @@ class MapperTest {
@Test @Test
void testEmptyFieldsMap() { void testEmptyFieldsMap() {
Source source = new Source(); Source source = new Source();
Object destination = Mapper.map(source, "np.com.krrish.Destination"); Object destination = Mapper.map(source, Destination.class);
assertEquals(Destination.class, destination.getClass()); assertEquals(Destination.class, destination.getClass());
} }
@ -19,7 +19,7 @@ class MapperTest {
source.setFirst("first"); source.setFirst("first");
source.setSecond("second"); source.setSecond("second");
Destination destination = (Destination) Mapper.map(source, "np.com.krrish.Destination"); Destination destination = (Destination) Mapper.map(source, Destination.class);
assertEquals("first", destination.getFirst()); assertEquals("first", destination.getFirst());
} }
} }

Loading…
Cancel
Save