读书人

利用反照技术实现POJO值拷贝

发布时间: 2012-11-05 09:35:12 作者: rapoo

利用反射技术实现POJO值拷贝

//原代码如下:

import java.lang.reflect.*;

public class ValueCopy{

?

/**

?*

?*功能:从第一个POJO(objFirst)类中将值拷贝到第二个POJO(objTwo)中去

?*

?*@Date:2008-12-08

?*

?*/
?public void valueCopy(Object objFirst,Object objTwo)throws Exception{
??Class<?> objFirstClass = objFirst.getClass();
??Class<?> objTwoClass = objTwo.getClass();
???????????????????????????? ?
??Field[] field = objTwoClass.getDeclaredFields();
??for(int i=0;i<field.length;i++){
???String fieldName = field[i].getName();
???String firstEdh = fieldName.substring(0,1).toUpperCase();
???String setMethodName = "set"+firstEdh+fieldName.substring(1);
???String getMethodName = "get"+firstEdh+fieldName.substring(1);
???
???Method getMethod = objFirstClass.getMethod(getMethodName,new Class[]{});
???Method setMethod = objTwoClass.getMethod(setMethodName,new Class[]{field[i].getType()});
???
???Object value = getMethod.invoke(objFirst,new Object[]{});
???setMethod.invoke(objTwo,new Object[]{value});
???
??}
??
?}
?
?public static void main(String[] args){
??UserForm userForm = new UserForm();
??userForm.setUsername("狂智");
??userForm.setPassword("123456");
??userForm.setEmail("ffr@163.com");
??userForm.setAge(24);
??
??User user = new User();
??try {
???new ValueCopy().valueCopy(userForm,user);
???
???
???Class userClass = user.getClass();
???System.out.println ("-------------"+user.getClass().getName()+"-------------");
???Field[] field = userClass.getDeclaredFields();
???for(int i=0;i<field.length;i++){
????String fieldName = field[i].getName();
????String firstEdh = fieldName.substring(0,1).toUpperCase();
????String getMethodName = "get"+firstEdh+fieldName.substring(1);
????
????Method getMethod = userClass.getMethod(getMethodName,new Class[]{});
????Object value = getMethod.invoke(user,new Object[]{});
????System.out.println (fieldName+": "+value);
???}
???System.out.println ("----------------结束----------------");
???
???
???? }
???? catch (Exception ex) {
???? ?ex.printStackTrace();
???? }
??
?}
}

读书人网 >软件架构设计

热点推荐