Skip to content

Instantly share code, notes, and snippets.

@Rayer
Created February 13, 2015 07:40
Show Gist options
  • Save Rayer/6c7547057adb99c74583 to your computer and use it in GitHub Desktop.
Save Rayer/6c7547057adb99c74583 to your computer and use it in GitHub Desktop.
New or initialize a object with a parent class instance
public class ObjectUtils {
public static <T> T initByParent(T target, Object parent) throws IllegalAccessException {
Class<?> parentClass = target.getClass().getSuperclass();
if(parent.getClass() != parentClass) {
throw new IllegalArgumentException("Invalid parent!");
}
Field[] fields = parentClass.getDeclaredFields();
for(Field f : fields) {
f.setAccessible(true);
f.set(target, f.get(parent));
}
return target;
}
public static <T> T initByParent(Class<?> targetClass, Object parent) throws IllegalAccessException, InstantiationException {
return (T)initByParent(targetClass.newInstance(), parent);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment