实体与对象的转换,有待完善
* @param getObj
* @param setObj
*/
public static void changeClass(Object getObj, Object setObj) {
try {
Field[] oldFields = getObj.getClass().getDeclaredFields();
Field[] newFields = setObj.getClass().getDeclaredFields();
Method[] getObjMethods = getObj.getClass().getMethods();
Method[] setObjMethods = setObj.getClass().getMethods();
for (Field newField : newFields) {
for (Field oldField : oldFields) {
if (oldField.getName().equals(newField.getName())) {
String fieldName = oldField.getName();
String get = "get" + fieldName.substring(0, 1).toUpperCase()
+ fieldName.substring(1, fieldName.length());
String set = "set" + fieldName.substring(0, 1).toUpperCase()
+ fieldName.substring(1, fieldName.length());
if (methodIsExist(get, getObjMethods)) {
Method getMethod = getObj.getClass().getDeclaredMethod(get);
Object param = getMethod.invoke(getObj);
if (param != null && methodIsExist(set, setObjMethods)) {
Method setMethod = setObj.getClass().getDeclaredMethod(set, param.getClass());
setMethod.invoke(setObj, param);
}
}
}
}
}
} catch (Exception e) {
System.out.println("绫诲瀷杞崲鍑洪敊锛?);
}
}
/**
* 楠岃瘉鏂规硶鏄惁瀛樺湪锛岄槻姝㈠嚭鐜癗oSuchMethodException
*
* @param str
* @param methods
* @return
*/
public static boolean methodIsExist(String str, Method[] methods) {
for (Method method : methods) {
if (str.equals(method.getName())) {
return true;
}
}
return false;
}
public static <T> T convertClass(Object obj, Class<T> cla) {
try {
T dataBean = null;
if (obj == null) {
return null;
}
//
Class<?> cls = obj.getClass();
Field[] fields = cls.getDeclaredFields();
Map<String, Object> maps = new HashMap<String, Object>();
for (Field field : fields) {
String fieldName = field.getName();
String get = "get" + fieldName.substring(0, 1).toUpperCase()
+ fieldName.substring(1, fieldName.length());
if (methodIsExist(get, cls.getMethods())) {
Method getMethod = cls.getMethod(get);
maps.put(fieldName, getMethod.invoke(obj));
}
}
//
dataBean = cla.newInstance();
Field[] beanFields = cla.getDeclaredFields();
for (Field field : beanFields) {
field.setAccessible(true);
String fieldName = field.getName();
Object fieldValue = maps.get(fieldName);
if (fieldValue != null) {
field.set(dataBean, fieldValue);
}
}
//
return dataBean;
} catch (Exception e) {
System.out.println("绫诲瀷杞崲鍑洪敊锛?);
return null;
}
}
欢迎关注公众号:Java后端技术全栈