BeanUtils與PropertyUtils的copyProperties方法的差別

1. copyProperties

        org.apache.commons.beanutils包中有兩個工具類,BeanUtils與PropertyUtils,這兩個工具類中各自有一個copyProperties(Object  dest, Object orig)方法,這兩個方法可以將兩個對象當中相同的屬性的值由源對象賦值至目標對象中。用到這個類的場景一般是由前臺傳到後臺的一個包裝類,將這個包裝類的值copy到一個實體對象中,由這個實體對象寫入數據庫表,可以省去多行get與set方法。

 

2. BeanUtils與PropertyUtils的copyProperties方法的差別

       這兩個工具類當中的copyProperties方法的方法名、參數,都一樣,所使用到的場景也類似,它們之間的差別在於源對象中int、值爲null的時候。以下用代碼說明,有一個User類,及一個繼承自該類的UserVO,這要做的事,是將User當中的屬性copy到UserVO當中。

 

3. 測試代碼

3.1 實體類

        下面有兩個實體類,其中一個實體類繼承自另一個實體類,測試代碼要做的事情就是將父類屬性的值賦到子類當中(由於篇幅原因,省去get、set與toString方法)。

import java.util.Date;

public class User {
	private Long id;
	
	private String name;
	
	private Integer sex;
	
	private Double age;
	
	private Date birthDay;
}
public class UserVO extends User{
	private String address;

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}
}

3.2 測試方法

        對於非null值的屬性,兩個工具類中的方法得到的結果是一樣的,那麼直接用null值來進行測試,測試方法如下:

import java.lang.reflect.InvocationTargetException;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.PropertyUtils;

public class Test01 {
	public static void main(String[] args) {
		// 原對象
		User sourceUser = new User();
		sourceUser.setId(null);
		sourceUser.setName(null);
		sourceUser.setAge(null);
		sourceUser.setSex(null);
		sourceUser.setBirthDay(null);
		// 目標對象
		UserVO destUser = new UserVO();
		// 測試BeanUtil
		testBeanUtil(destUser, sourceUser);
		// 測試PropertyUtil
		testPropertyUtil(destUser, sourceUser);
		
	}
	
	private static void testBeanUtil(User destUser, User sourceUser) {
		try {
			BeanUtils.copyProperties(destUser, sourceUser);
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
		System.out.println("BeanUtils result:" + destUser);
	}
	
	private static void testPropertyUtil(User destUser, User sourceUser) {
		try {
			PropertyUtils.copyProperties(destUser, sourceUser);
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		}
		System.out.println("PropertyUtils result:" + destUser);
	}
}

3.3 輸出結果

BeanUtils result:User [id=0, name=null, sex=0, age=0.0, birthDay=null, address=null]
PropertyUtils result:User [id=null, name=null, sex=null, age=null, birthDay=null, address=null]

        由打印的結果可以看到,Long類型、Integer類型、Double類型的值如果爲空,調用BeanUtils的copyProperties方法地到的結果會將這些類型的值賦爲0或者0.0,而使用PropertyUtils的copyProperties方法源對象與目標對象的值是一樣的。

 

4. 結論

        使用org.apache.commons.beanutils.BeanUtils的copyProperties方法得到的結果會將爲null的Integer、Long、Double類型的屬性賦值爲0或者0.0,但對於String、Date等類則不會有這種結果(null依然爲null),而使用org.apache.commons.beanutils.BeanUtils的copyProperties方法得到的結果不會給null值賦初始值(null依然爲null)。所以在實際的開發中碰到類似的業務場景需要正確選用合適的工具類。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章