/** * 浅拷贝的工具类 */ public class PropertiesUtil { /** * 两个类,属性名一样的元素,复制成员。 */ public static void copy(Object source,Object target){ Class<?> sourceClass=source.getClass(); Class<?> targetClass=target.getClass(); Field [] sourceFields=sourceClass.getDeclaredFields(); //遍历成员 for (int i = 0; i < sourceFields.length; i++) { //获取第i个元素 Field field=sourceFields[i]; //设置可见性 field.setAccessible(true); //拿到成员名 String name = field.getName(); Field targetField=null; try { targetField = targetClass.getDeclaredField(name); } catch (NoSuchFieldException e) { //e.printStackTrace(); continue; } //复制属性的值 targetField.setAccessible(true); try { targetField.set(target,field.get(source)); } catch (IllegalAccessException e) { e.printStackTrace(); } } } /** * 两个类,属性名一样的元素,复制成员。 */ public static <T> T copy(Object source,Class<T> targetClass){ Class<?> sourceClass=source.getClass(); T target= null; try { target = targetClass.newInstance(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } Field [] sourceFields=sourceClass.getDeclaredFields(); //遍历成员 for (int i = 0; i < sourceFields.length; i++) { //获取第i个元素 Field field=sourceFields[i]; //设置可见性 field.setAccessible(true); //拿到成员名 String name = field.getName(); Field targetField=null; try { targetField = targetClass.getDeclaredField(name); } catch (NoSuchFieldException e) { //e.printStackTrace(); continue; } //复制属性的值 targetField.setAccessible(true); try { targetField.set(target,field.get(source)); } catch (IllegalAccessException e) { e.printStackTrace(); } } return target; } // public static void main(String[] args) { // UserVO user1=new UserVO(); // UserVO user2=new UserVO(); // user1.setId(1L); // user1.setUsername("zhangsan"); // copy(user1,user2); // System.out.println(user2); // } }