java將父類全部的屬性COPY到子類中

public class FatherToChildUtils {
    /* 
     * 將父類全部的屬性COPY到子類中。 
     * 類定義中child必定要extends father; 
     * 並且child和father必定爲嚴格javabean寫法,屬性爲deleteDate,方法爲getDeleteDate 
     */  
    public static void fatherToChild (Object father,Object child){  
        if(!(child.getClass().getSuperclass()==father.getClass())){  
            System.err.println("child不是father的子類"); 
        }  
        Class fatherClass= father.getClass();  
        Field ff[]= fatherClass.getDeclaredFields();  
        for(int i=0;i<ff.length;i++){  
            Field f=ff[i];//取出每個屬性,如deleteDate  
            Class type=f.getType();  
            try {
                Method m = fatherClass.getMethod("get"+upperHeadChar(f.getName()));//方法getDeleteDate  
                Object obj=m.invoke(father);//取出屬性值               
                f.set(child,obj);
            } catch (SecurityException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IllegalArgumentException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (NoSuchMethodException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }  
        }  
    }  
    /** 
     * 首字母大寫,in:deleteDate,out:DeleteDate 
     */  
    private static String upperHeadChar(String in){  
        String head=in.substring(0,1);  
        String out=head.toUpperCase()+in.substring(1,in.length());  
        return out;  
    }  

}
相關文章
相關標籤/搜索