java-实体类属性的复制(将一个实体类转为另一个实体类)

package gwxm.sffw.result.utils;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import gwxm.sffw.result.entity.TZtzdyjYcsbls;
import gwxm.sffw.result.entity.TZtzdyjYcsbss;

public class JavaBeanUtil {
	 
	
	/**
	 * 
	 * @param source 被复制的实体类对象
	 * @param to 复制完后的实体类对象  
	 * @throws Exception
	 */
	public static void Copy(Object source, Object to) throws Exception {  
        // 获取属性  
        BeanInfo sourceBean = Introspector.getBeanInfo(source.getClass(),java.lang.Object.class);  
        PropertyDescriptor[] sourceProperty = sourceBean.getPropertyDescriptors();  
  
        BeanInfo destBean = Introspector.getBeanInfo(to.getClass(),java.lang.Object.class);  
        PropertyDescriptor[] destProperty = destBean.getPropertyDescriptors();  
  
        try {  
            for (int i = 0; i < sourceProperty.length; i++) {  
                for (int j = 0; j < destProperty.length; j++) {  
                    if (sourceProperty[i].getName().equals(destProperty[j].getName())) {  
                        // 调用source的getter方法和dest的setter方法  
                        destProperty[j].getWriteMethod().invoke(to,sourceProperty[i].getReadMethod().invoke(source));  
                        break;  
                    }  
                }  
            }  
        } catch (Exception e) {  
            throw new Exception("属性复制失败:" + e.getMessage());  
        }  
    }  
	public static void main(String args[]) throws Exception{
		TZtzdyjYcsbls ls = new TZtzdyjYcsbls();
		TZtzdyjYcsbss ss=new TZtzdyjYcsbss();
		ss.setBdzid("1");
		ss.setCnr("fuxiaop");
		ss.setSbmc("变压器");
		
		Copy(ss,ls);
		System.out.println(ls.toString());
	}
}

 

你可能感兴趣的:(Java)