---
title: "利用反射技术实现POJO值拷贝"
author: "lcb530"
date: "2008-12-08T18:07:49Z"
tags: []
categories: ["企业架构"]
slug: "pojo"
draft: false
lastmod: "2008-12-08T18:07:49Z"
id: 288977
url: "https://lcb530.iteye.com/blog/288977"
---

//原代码如下:

import java.lang.reflect.\*;

public class ValueCopy{

 

/\**

 *

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

 *

 [\*@Date:2008-12-08](mailto:*@Date:2008-12-08)

 *

 \*/  
 public void valueCopy(Object objFirst,Object objTwo)throws Exception{  
  Class&lt;?&gt; objFirstClass = objFirst.getClass();  
  Class&lt;?&gt; objTwoClass = objTwo.getClass();  
                                
  Field\[] field = objTwoClass.getDeclaredFields();  
  for(int i=0;i&lt;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](mailto: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&lt;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();  
     }  
    
 }  
}