Skip to content

Instantly share code, notes, and snippets.

@benjamin-ict
Created July 23, 2020 18:05
Show Gist options
  • Save benjamin-ict/ca9d44cdd73ced17ac8a875e6bd8772d to your computer and use it in GitHub Desktop.
Save benjamin-ict/ca9d44cdd73ced17ac8a875e6bd8772d to your computer and use it in GitHub Desktop.
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