方式一:
private void fatherToChild(Object father, Object child) {
if (!(child.getClass().getSuperclass() == father.getClass())) {
try {
throw new Exception(child + "不是" + father + "的子類");
} catch (Exception e) {
e.printStackTrace();
}
}
Class fatherClass = father.getClass();
Field[] fatherClassDeclaredFields = fatherClass.getDeclaredFields();
for (Field tmpField : fatherClassDeclaredFields) {
Method method = null;
try {
method = fatherClass.getMethod("get" + upperHeadChar(tmpField.getName()));
Object invoke = method.invoke(father);
tmpField.set(child, invoke);
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* 首字母大寫
*
* @param name
* @return
*/
private String upperHeadChar(String name) {
String head = name.substring(0, 1);
return head.toUpperCase() + name.substring(1, name.length());
}
方式二:
setter
方式一個一個進行賦值