前段时间写项目的时候需要把2个不同的类中相同属性的值复制一下,虽然已经包做了这项事情,但是不知道会不会符合自己的要求,所以自己写了一个,只是最简单的,而且参考了网上的一些其他人的代码:
public class CopyUtil { /** * 把from对象中的属性值copy给to对象中属性值相同的 </br> * (简单copy,只能copy基本数据类型的属性) * @param from * @param to */ public static void copy(Object from,Object to){ Method[] fromMethods = from.getClass().getDeclaredMethods(); Method[] toMethods = to.getClass().getDeclaredMethods(); for (Method fromMethod : fromMethods) { //获取from对象的get方法 String fromMethodName = fromMethod.getName(); if(!fromMethodName.contains("get")){ continue; } String fromstr = fromMethodName.substring(3); String fromPro = fromstr.substring(0, 1).toLowerCase()+fromstr.substring(1); for (Method toMethod : toMethods) { //获取to对象的set方法 String toMethodName = toMethod.getName(); if(!toMethodName.contains("set")){ continue; } String tostr = toMethodName.substring(3); String toPro = tostr.substring(0, 1).toLowerCase()+tostr.substring(1); //属性名相同则copy if(fromPro.equals(toPro)){ try { Object value = fromMethod.invoke(from, new Object[0]); if(value == null){ continue; } toMethod.invoke(to, new Object[]{value}); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } } } } }