JavaBean的值複製工具

penweizgx發表於2010-09-05
我想寫一個JavaBean的值複製,用於對JavaBean比較覆蓋其屬性值;
現在基本資料型別的能夠正常複製成功,但關聯的物件屬性就不行了,請問怎麼修改?

	public static void copy(Object dest ,Object src){
		if(dest.getClass()==src.getClass()){
			Field[] destField = dest.getClass().getDeclaredFields();
			Field[] srcField = src.getClass().getDeclaredFields();
			for(int i=0;i<destField.length;i++){
				String destFieldName = destField[i].getName();
				String destFieldType = destField[i].getGenericType().toString();
				for(int n=0;n<srcField.length;n++){
					String srcFieldName = srcField[n].getName();
					String srcFieldType = srcField[n].getGenericType().toString();
					  if(destFieldName.equals(srcFieldName)&&destFieldType.equals(srcFieldType)){
						  destField[i].setAccessible(true);
						  srcField[n].setAccessible(true);
						  Object srcobj = null;
						  try {
							srcobj =  srcField[n].get(src);
							if(srcobj!=null){
								srcField[n].set(dest, srcobj);
							}
						} catch (IllegalArgumentException e) {
							e.printStackTrace();
						} catch (IllegalAccessException e) {
							e.printStackTrace();
						}
						
					  }
				}
			}
		}
	}
<p class="indent">

相關文章