1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| public class CopyFatherToChild { public static void main(String[] args) throws Exception { A a=new A(); B b=new B(); a.setA("a"); a.setB("b"); b.setC("c"); b.setD("d"); fatherToChild(a,b); System.out.println(b); }
public static <T>void fatherToChild(T father,T child) throws Exception { if (child.getClass().getSuperclass()!=father.getClass()){ throw new Exception("child 不是 father 的子类"); } Class<?> fatherClass = father.getClass(); Field[] declaredFields = fatherClass.getDeclaredFields(); for (int i = 0; i < declaredFields.length; i++) { Field field=declaredFields[i]; Method method=fatherClass.getDeclaredMethod("get"+upperHeadChar(field.getName())); Object obj = method.invoke(father); field.setAccessible(true); field.set(child,obj); }
}
public static String upperHeadChar(String in) { String head = in.substring(0, 1); String out = head.toUpperCase() + in.substring(1, in.length()); return out; } }
|