Created
July 23, 2020 18:05
-
-
Save benjamin-ict/ca9d44cdd73ced17ac8a875e6bd8772d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.lang.reflect.Field; | |
import java.lang.reflect.InvocationTargetException; | |
import java.lang.reflect.Modifier; | |
import java.util.Date; | |
public class ModelHelper { | |
public static <T> T merge(T local, T remote) | |
throws IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException { | |
Class<?> clazz = local.getClass(); | |
Object merged = clazz.getConstructor().newInstance(); | |
for (Field field : clazz.getDeclaredFields()) { | |
field.setAccessible(true); | |
Object localValue = field.get(local); | |
Object remoteValue = field.get(remote); | |
if (!Modifier.isFinal(field.getModifiers())) { | |
if (localValue != null) { | |
field.set(merged, (remoteValue != null) ? remoteValue : localValue); | |
} else if (remoteValue != null) { | |
field.set(merged, remoteValue); | |
} | |
} | |
} | |
//noinspection unchecked | |
return (T) merged; | |
} | |
public static <T> T mock(Class<T> clazz) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException { | |
T object = clazz.getConstructor().newInstance(); | |
for (Field field : clazz.getDeclaredFields()) { | |
field.setAccessible(true); | |
if (field.getType().isAssignableFrom(String.class)) { | |
field.set(object, field.getName()); | |
} else if (field.getType().isAssignableFrom(Double.class)) { | |
field.set(object, 0.0); | |
} else if (field.getType().isAssignableFrom(Integer.class)) { | |
field.set(object, 0); | |
} else if (field.getType().isAssignableFrom(Long.class)) { | |
field.set(object, 0L); | |
} else if (field.getType().isAssignableFrom(Date.class)) { | |
field.set(object, new Date()); | |
} else if (field.getType().isAssignableFrom(Boolean.class)) { | |
field.set(object, Boolean.TRUE); | |
} else if (field.getType().isAssignableFrom(Float.class)) { | |
field.set(object, 0f); | |
} else { | |
field.set(object, mock(field.getType())); | |
} | |
} | |
return object; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment