Created
February 13, 2015 07:40
-
-
Save Rayer/6c7547057adb99c74583 to your computer and use it in GitHub Desktop.
New or initialize a object with a parent class instance
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
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