commons-beanutils BeanUtils copyProperties 对象复制 使用
pom.xml:
1 <project xmlns="http://maven.apache.org/POM/4.0.0" 2 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 3 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4 <modelVersion>4.0.0</modelVersion> 5 <groupId>test.beanutils</groupId> 6 <artifactId>beanutils</artifactId> 7 <version>0.0.1-SNAPSHOT</version> 8 <dependencies> 9 <dependency> 10 <groupId>commons-beanutils</groupId> 11 <artifactId>commons-beanutils</artifactId> 12 <version>1.8.3</version> 13 </dependency> 14 <dependency> 15 <groupId>junit</groupId> 16 <artifactId>junit</artifactId> 17 <version>4.8.2</version> 18 </dependency> 19 </dependencies> 21 </project>
User.java:
1 package com.zjc.bean; 2 3 public class User { 4 private int id; 5 private String name; 6 private int age; 7 8 public int getId() { 9 return id; 10 } 11 public void setId(int id) { 12 this.id = id; 13 } 14 public String getName() { 15 return name; 16 } 17 public void setName(String name) { 18 this.name = name; 19 } 20 public int getAge() { 21 return age; 22 } 23 public void setAge(int age) { 24 this.age = age; 25 } 26 }
测试类Manage.java:
1 import java.lang.reflect.InvocationTargetException; 2 3 import org.apache.commons.beanutils.BeanUtils; 4 import org.junit.Test; 5 6 import com.zjc.bean.User; 7 8 9 public class Manage { 10 11 @Test 12 public void propertyCopy() { 13 User user = new User(); 14 User otherUser = new User(); 15 16 user.setId(1); 17 user.setName("wangwu"); 18 user.setAge(12); 19 20 try { 21 BeanUtils.copyProperties(otherUser, user); 22 } catch (IllegalAccessException e) { 23 // TODO Auto-generated catch block 24 e.printStackTrace(); 25 } catch (InvocationTargetException e) { 26 // TODO Auto-generated catch block 27 e.printStackTrace(); 28 } 29 30 System.out.println(otherUser.getId() + "," + otherUser.getName() + "," + otherUser.getAge()); 31 } 32 }
好处:避免了繁琐的get和set方法。
posted on 2013-08-12 11:49 zenger1025 阅读(821) 评论(0) 收藏 举报
浙公网安备 33010602011771号