您的位置:首页 > 其它

利用发射进行对象赋值

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;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  反射 赋值