利用java反射机制实现对象值拷贝

首先需求是这样的 ,我把它简化一下:

User user1=new User();
user1.setUserName("wxn");
User user2=new User();
user2.setUserName("kkkk");
User user3=user2;

接下来的操作我想让user2中的值和user1中的值全部相等。我们知道可以通过 user2=user1.clone()方法去获得一个新的对象,这种方法的详细介绍在这里可以学习。http://www.cnblogs.com/yxnchinahlj/archive/2010/09/20/1831615.html

但是这样clone出来的是一个新的对象,user2就是user1的一个新对象的拷贝,虽然user2中的值可以和user1中的值相等,但是 user3就已经不是user2之前的对象了,我需要user3中的值也跟着改变。

于是最简单的方法就是在User类中增加一个方法

public void copy(User user){
    this.setUserName(user.getUserName);
    this.setUserId(user.setUserId);
     .....
}

如果user中的属性太多怎么办?那写起来太麻烦了,除了方法名get和set有区别之外没什么区别, 于是我想起了之前看过的java反射机制来批量处理,顺便巩固一下java的反射机制,实现代码如下

public void copy(User user) {
//获得User类中所有的方法
		Method[] methods = user.getClass().getMethods();
		try {
		for (int i = 0; i < methods.length; i++) {
				String mName = methods[i].getName();
				if (mName.startsWith("set")) {
					String nName =null;
					//若为boolean的属性则没有get方法 只有 isXXX方法
					 if(boolean.class.equals(methods[i].getParameterTypes()[0]) ){
						  nName=mName.replace("set", "is");
					  }	else{
						  nName=mName.replace("set", "get");
					  }
					Method method = user.getClass().getDeclaredMethod(nName,
							null);
					methods[i].invoke(this, method.invoke(user, null));
				}

			} 
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

全部代码如下


import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 
 * @author ahsiu
 * 
 */

public class User {
	private int userId;
	private String userName;
	private String password;
	private String email;
	private String phone;
	private int loginState;
   private boolean flag;
	public int getUserId() {
		return userId;
	}

	public void copy(User user) {
		Method[] methods = user.getClass().getMethods();
		try {
			for (int i = 0; i < methods.length; i++) {
				String mName = methods[i].getName();
				if (mName.startsWith("set")) {

					String nName =null;
					//若为boolean的属性则没有get方法 只有 isXXX方法
					 if(boolean.class.equals(methods[i].getParameterTypes()[0]) ){
						  nName=mName.replace("set", "is");
					  }	else{
						  nName=mName.replace("set", "get");
					  }

					Method method = user.getClass().getDeclaredMethod(nName,
							null);
					methods[i].invoke(this, method.invoke(user, null));

				}

			}
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void setUserId(int userId) {
		this.userId = userId;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public String getPhone() {
		return phone;
	}

	public void setPhone(String phone) {
		this.phone = phone;
	}

	public int getLoginState() {
		return loginState;
	}

	public void setLoginState(int loginState) {
		this.loginState = loginState;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public boolean isFlag() {
		return flag;
	}

	public void setFlag(boolean flag) {
		this.flag = flag;
	}

	public static void main(String[] args) {
		User user1=new User();
		user1.setUserName("wxn");
		User user2=new User();
		user2.setUserName("kkkk");
		User user3=user2;
		System.out.println(user1.getUserName());
		System.out.println(user2.getUserName());
		System.out.println(user3.getUserName());	
		System.out.println("");
		user2.copy(user1);
		System.out.println(user1.getUserName());
		System.out.println(user2.getUserName());
		System.out.println(user3.getUserName());
		System.out.println("");
		user3.setUserName("ahsiu");
		System.out.println(user1.getUserName());
		System.out.println(user2.getUserName());
		System.out.println(user3.getUserName());
	}
}

发表评论

电子邮件地址不会被公开。 必填项已用*标注