在 Java 開發中,頻繁撰寫 getter/setter 進行屬性複製不僅繁瑣,也容易因疏失導致錯誤。Apache Commons BeanUtils 提供 BeanUtils.copyProperties() 方法,可一次將來源物件的所有屬性複製至目標物件,大幅簡化程式碼。
import org.apache.commons.beanutils.BeanUtils;
public class CopyDemo {
public static void main(String[] args) {
TUser user = new TUser();
user.setName("Emma");
user.setUserType(1);
TUser anotherUser = new TUser();
try {
BeanUtils.copyProperties(anotherUser, user);
System.out.println("UserName => " + anotherUser.getName());
System.out.println("UserType => " + anotherUser.getUserType());
} catch (IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
}
}
IllegalAccessException 與 InvocationTargetException,務必捕獲處理。善用工具庫,讓程式碼更簡潔、可維護性更高。