---
title: "数据源复制Util"
author: "DannyWei"
date: "2014-02-27T09:41:27Z"
tags: []
categories: ["企业架构"]
slug: "util"
draft: false
lastmod: "2014-02-27T09:41:27Z"
id: 2023041
url: "https://dannywei.iteye.com/blog/2023041"
---

有时候我们在开发过程中经常会遇到,将一个对象的数据复制到另外一个对象里面去，比如要讲一个对象的数据复制到一个历史记录表里面去，如果我们用set ,get 就比较麻烦，用这个目前类的前提是，javaBean实体里面的属性是相同的才可以复制，这样可以大大提高了我们在开发过程中的数据操作时间。


```java

import java.lang.reflect.Method;
/**
 * 数据源复制util
 * @author weidetian
 * @version 2013-12-16
 */
public class BeanUtil {
	public static void copyProperties(Object source, Object dest)
			throws Exception {
		Method[] sourceMethod = source.getClass().getMethods();
		Method[] destMethod = dest.getClass().getMethods();
		String sourceMethodName, methodFix1, destMethodName2, methodFix2;
		for (int i = 0; i < sourceMethod.length; i++) {
			sourceMethodName = sourceMethod[i].getName();
			methodFix1 = sourceMethodName.substring(3,
					sourceMethodName.length());
			if (sourceMethodName.startsWith("get")) {
				for (int j = 0; j < destMethod.length; j++) {
					destMethodName2 = destMethod[j].getName();
					methodFix2 = destMethodName2.substring(3,
							destMethodName2.length());
					if (destMethodName2.startsWith("set")) {
						if (methodFix2.equals(methodFix1)) {
							Object[] objs2 = new Object[1];
							objs2[0] = sourceMethod[i].invoke(source,
									new Object[0]);
							// 只copy不为空的值
							if (null != objs2[0]) {
								destMethod[j].invoke(dest, objs2);
							}
							continue;
						}
					}
				}
			}
		}
	}


}


```