public classTest {/*** origin字段向target转化
*@paramorigin
*@paramtarget
*@return
*/
public static T swap(Object origin,T target){
Field[] tFs= target.getClass().getDeclaredFields();//获得属性
Field[] oFs = origin.getClass().getDeclaredFields();//获得属性
for(int i=0;i
String tname=tFs[i].getName();for(int j=0;j
Object val=getValue(origin, tname);
setValue(target, tname, val);
}
}
}returntarget;
}/***
*@parambeanObj 实体类*/
private staticObject getValue(Object beanObj,String name){try{
Field[] fields= beanObj.getClass().getDeclaredFields();//获得属性
Class clazz =beanObj.getClass();for (int i = 0; i < fields.length; i++) {
Field field=fields[i];
String names=field.getName();if(!names.equals(name)){continue;
}//此处应该判断beanObj,property不为null
PropertyDescriptor pd = newPropertyDescriptor(field.getName(), clazz);
Method getMethod=pd.getReadMethod();if (getMethod != null) {//System.out.println(beanObj+"的字段是:"+field.getName()+",类型是:"+field.getType()+",取到的值是: "+getMethod.invoke(beanObj));
returngetMethod.invoke(beanObj);
}
}
}catch(Exception e) {
e.printStackTrace();
}return null;
}/***
*@parambeanObj 实体类
*@paramname 字段名
*@paramvalue 值*/
private static voidsetValue(Object beanObj,String name,Object value){try{
Field[] fields= beanObj.getClass().getDeclaredFields();//获得属性
Class clazz =beanObj.getClass();for (int i = 0; i < fields.length; i++) {
Field field=fields[i];
String names=field.getName();if(!names.equals(name)){continue;
}
PropertyDescriptor pd= newPropertyDescriptor(field.getName(), beanObj.getClass());
Method setMethod=pd.getWriteMethod();if (setMethod != null) {
setMethod.invoke(beanObj, value);
}
}
}catch(Exception e) {
e.printStackTrace();
}
}
}