import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
/***
* A类中的某些属性在B类中存在,把相同的属性从A类复制到B类
*/
public class AttributeTransferUtil {
private static Logger logger = LoggerFactory.getLogger(AttributeTransferUtil.class);
public static Object cloneAttribute(Object clone, Object beCloned){
Field[] fieldClone = null;
Field[] fieldBeCloned = null;
Map<String, Field> map = new HashMap<String, Field>();
try {
Class<?> classClone = clone.getClass();
Class<?> classBecloned = beCloned.getClass();
fieldClone = classClone.getDeclaredFields();
fieldBeCloned = classBecloned.getDeclaredFields();
for (int i = 0; i < fieldBeCloned.length; i++) {
map.put(fieldBeCloned[i].getName(), fieldBeCloned[i]);
}
for (int j = 0; j < fieldClone.length; j++) {
String fieldCloneName = fieldClone[j].getName();
Field field = map.get(fieldCloneName);
if (field != null) {
Method getMethod = classClone.getMethod(getMethodName(fieldCloneName));
Method setMethod = classBecloned.getMethod(setMethodName(fieldCloneName), field.getType());
setMethod.invoke(beCloned, getMethod.invoke(clone));
}
}
} catch (Exception ex) {
logger.error(ex.getMessage());
} finally {
fieldClone = null;
fieldBeCloned = null;
map.clear();
}
return beCloned;
}
private static String getMethodName(String fieldName){
String head = fieldName.substring(0, 1).toUpperCase();
String tail = fieldName.substring(1);
return "get" + head + tail;
}
private static String setMethodName(String fieldName){
String head = fieldName.substring(0, 1).toUpperCase();
String tail = fieldName.substring(1);
return "set" + head + tail;
}
}