通过反射,给对象之间赋值
2014-11-24 14:18
369 查看
/**
* 通过反射,给对象赋值
* add by wangHao 2014-01-08
* @param source
* @param dest
* @throws Exception
*/
public void CopyObject(Object source,Object dest)throws Exception {
BeanInfo sourceBean = Introspector.getBeanInfo(source.getClass(), java.lang.Object.class);
PropertyDescriptor[] sourceProperty = sourceBean.getPropertyDescriptors();
BeanInfo destBean = Introspector.getBeanInfo(dest.getClass(), java.lang.Object.class);
PropertyDescriptor[] destProperty = destBean.getPropertyDescriptors();
try{
for(int i=0;i<sourceProperty.length;i++){
if( "id".equals(sourceProperty[i].getName())){
continue;
}
for(int j=0;j<destProperty.length;j++){
if(sourceProperty[i].getName().equals(destProperty[j].getName())){
destProperty[j].getWriteMethod().invoke(dest, sourceProperty[i].getReadMethod().invoke(source));
break;
}
}
}
}catch(Exception e){
throw new Exception("属性复制失败:",e);
}
}
* 通过反射,给对象赋值
* add by wangHao 2014-01-08
* @param source
* @param dest
* @throws Exception
*/
public void CopyObject(Object source,Object dest)throws Exception {
BeanInfo sourceBean = Introspector.getBeanInfo(source.getClass(), java.lang.Object.class);
PropertyDescriptor[] sourceProperty = sourceBean.getPropertyDescriptors();
BeanInfo destBean = Introspector.getBeanInfo(dest.getClass(), java.lang.Object.class);
PropertyDescriptor[] destProperty = destBean.getPropertyDescriptors();
try{
for(int i=0;i<sourceProperty.length;i++){
if( "id".equals(sourceProperty[i].getName())){
continue;
}
for(int j=0;j<destProperty.length;j++){
if(sourceProperty[i].getName().equals(destProperty[j].getName())){
destProperty[j].getWriteMethod().invoke(dest, sourceProperty[i].getReadMethod().invoke(source));
break;
}
}
}
}catch(Exception e){
throw new Exception("属性复制失败:",e);
}
}
相关文章推荐
- 代码 - 通过反射对象属性进行遍历赋值
- 干货 java jdbc ResultSet结果通过java反射赋值给java对象
- 对象之间通过反射拷贝数据
- 通过反射将数组中的元素给一个对象中的各个字段赋值
- C#通过反射给对象赋值
- 随机让对象中的属性赋值,不通过过判断(通过反射)
- C# 通过反射为一个对象赋值
- Reflect 通过反射获取自定义注解值给另外一个对象赋值
- Reflect 通过反射获取自定义注解值给另外一个对象赋值
- java通过反射,泛型将定义的对象与对象之间互转
- Reflect 通过反射获取自定义注解值给另外一个对象赋值
- 通过反射完成不同对象之间的属性拷贝
- .NET解析xml字符串,通过反射给实体类对象赋值,获取实体类数据列表
- (Siverlight应用程序之间)通过宿主(B屏)New对象,进行的交互消息(反射)
- 通过内核对象在服务程序和桌面程序之间通信
- 通过反射访问对象私有和保护成员
- 通过反射的方法,将源对象属性的值赋给目标对象的相同属性(举例)
- 通过反射的方法,将源对象属性的值赋给目标对象的相同属性
- 通过反射给窗体赋值
- 通过反射访问对象私有和保护成员