ITeye博客

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

lcb530 · 2008-12-08 18:07 · Java · 企业架构 · Markdown

//原代码如下:

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();
     }
  
 }
}

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。