利用发射进行对象赋值
2017-04-13 16:17
260 查看
/** * 两个相同属性的对象赋值 * * @param sourceObj * @param targetObj */ public static void entityPropertiesCopy(Object sourceObj, Object targetObj) { if (sourceObj == null || targetObj == null) return; Class targetClass = null; //用java反射机制就可以, 可以做成通用的方法, 只要属性名和类型一样 Field[] sourceFields = null; try { targetClass = targetObj.getClass(); sourceFields = sourceObj.getClass().getDeclaredFields(); } catch (Exception e) { e.printStackTrace(); } String fieldName = ""; Class fieldType = null; for (int i = 0; i < sourceFields.length; i++) { try { fieldName = sourceFields[i].getName(); fieldType = sourceFields[i].getType(); Field targetField = targetClass.getDeclaredField(fieldName); if (targetField != null && targetField.getType().equals(fieldType)) { Method sourceGetter = sourceObj.getClass().getMethod(getGetMethodName(fieldName)); Method targetSetter = targetObj.getClass().getMethod(getSetMethodName(fieldName), new Class<?>[]{fieldType}); Object fieldValue = sourceGetter.invoke(sourceObj); if (fieldValue != null) { targetSetter.invoke(targetObj, new Object[]{fieldValue}); } } } catch (NoSuchFieldException e) { } catch (Exception e) { e.printStackTrace(); } } } public static String getGetMethodName(String fieldName) { String result = fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1); return "get" + result; } public static String getSetMethodName(String fieldName) { String result = fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1); return "set" + result; }
相关文章推荐
- 利用发反射对对象进行赋值
- 利用operator关键字在对象间进行赋值的几点注意事项(1)
- 利用operator关键字在对象间进行赋值的几点注意事项(2)
- 利用java反射机制进行对象操作
- 掌握 Ajax,第 4 部分: 利用 DOM 进行 Web 响应 将 HTML 转换为对象模型
- js混淆代码还原-js反混淆:利用js进行赋值实现
- 利用dynamic解决匿名对象不能赋值的问题
- [c#] 利用序列化进行对象深度clone
- 利用序列化与反序列化对Java对象进行深度复制
- js混淆代码还原-js反混淆:利用js进行赋值实现
- js混淆代码还原-js反混淆:利用js进行赋值实现
- c# 利用反射动态给实体类对象赋值
- 笔记—利用反射给对象赋值
- 利用PagedDataSource 对象进行分页
- C#自动给据sql中的带@的变量提取变量名称在从简单数据对象中取得生成SqlParameter数组进行数据插入(利用反射完成)
- 利用反射对对象属性赋值取值操作
- DBController心得之一:利用DMO对象对SQL2005数据库进行Backup和restore的操作 推荐
- C#自动给据sql中的带@的变量提取变量名称在从简单数据对象中取得生成SqlParameter数组进行数据插入(利用反射完成)
- 对象转换对同属性进行赋值
- 利用C#对word中的书签位置进行赋值