java 父類對象賦值給子類

方式一:

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 方式一個一個進行賦值

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章