生活随笔
收集整理的這篇文章主要介紹了
复制类中的属性值到另一个类的相同属性中
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
代碼有好多高級代碼,現在給大家看一個,就是復制相同屬性的值到另一個類。
例如:A類中有String name,int score;B類中有String name ,int score,String schoole,現在想把A類中的name和score的值復制到B中,就可以使用下面的方法,我感覺代碼寫的不錯,我們都學習一下:
public static void copy(Object source, Object target) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, InvocationTargetException {Class sourceClass = source.getClass();//得到對象的ClassClass targetClass = target.getClass();//得到對象的ClassField[] sourceFields = sourceClass.getDeclaredFields();//得到Class對象的所有屬性Field[] targetFields = targetClass.getDeclaredFields();//得到Class對象的所有屬性for(Field sourceField : sourceFields){String name = sourceField.getName();//屬性名Class type = sourceField.getType();//屬性類型String methodName = name.substring(0, 1).toUpperCase() + name.substring(1);Method getMethod = sourceClass.getMethod("get" + methodName);//得到屬性對應get方法Object value = getMethod.invoke(source);//執行源對象的get方法得到屬性值for(Field targetField : targetFields){String targetName = targetField.getName();//目標對象的屬性名if(targetName.equals(name)){Method setMethod = targetClass.getMethod("set" + methodName, type);//屬性對應的set方法setMethod.invoke(target, value);//執行目標對象的set方法}}}}
總結
以上是生活随笔為你收集整理的复制类中的属性值到另一个类的相同属性中的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。