在J2EE框架中用到了很多JAVA EBAN,如struts 中的actionform、hibernate中的PO、VO,并在各个BEAN中复制,在struts的org.apache.commons.beanutils.BeanUtils.copyProperties方法中就可以做到BEAN的复制,下面是使用JAVA反射机制实现这一方法;
类Person
- package accessingprivate;
- public class Person {
- private String name;
- private String address;
- int age;
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public String getAddress() {
- return address;
- }
- public void setAddress(String address) {
- this.address = address;
- }
- public int getAge() {
- return age;
- }
- public void setAge(int age) {
- this.age = age;
- }
- }
类People
- package accessingprivate;
- public class People {
- private String name;
- private int age;
- private String email;
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public String getEmail() {
- return email;
- }
- public void setEmail(String email) {
- this.email = email;
- }
- public int getAge() {
- return age;
- }
- public void setAge(int age) {
- this.age = age;
- }
- }
类BeanCopy
- package accessingprivate;
- import java.lang.reflect.Field;
- public class BeanCopy {
- /**
- * @param args
- */
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- Person person = new Person();
- People people = new People();
- person.setName("ALEX");
- person.setAddress("");
- person.setAge(36);
- try {
- copy(people,person);
- } catch (Exception e) {
- e.printStackTrace();
- }
- System.out.println(people.getName()+"-->"+people.getAge());
- }
- public static void copy(Object obj,Object object) throws Exception{
- Field [] fieldobject = object.getClass().getDeclaredFields();
- Field [] fieldob = obj.getClass().getDeclaredFields();
- for(int i=0; i<fieldobject.length;i++){
- String objectname = fieldobject[i].getName();
- String objDataType = (fieldobject[i].getGenericType()).toString();
- for(int j=0; j<fieldob.length;j++){
- String objname = fieldob[j].getName();
- String objectDataType = (fieldob[j].getGenericType()).toString();
- if(objname.equals(objectname)&&objDataType.equals(objectDataType)){
- fieldobject[i].setAccessible(true);
- fieldob[j].setAccessible(true);
- Object objs = fieldobject[i].get(object);
- fieldob[j].set(obj, objs);
- }
- }
- }
- }
- }
输出结果: ALEX-->36