Java對象轉換(Map轉換Object或者反轉)__Java

來源:互聯網
上載者:User

Map轉換Object、Object轉換Map、List<Object>轉換List<Map>、List<Map>轉換List<Object>、對象拷貝

package cn.framework.util; import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;


import javax.servlet.http.HttpServletRequest;


/**
 * 對象類進階操作
 * 
 * @author jonas
 * 
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
public class ObjectUtil {


/**
* 兩個相同類型對象覆蓋(oldObj覆蓋newObj,isNullReplace當oldObj欄位值為空白是否覆蓋,true覆蓋,false不覆蓋)

* @author jonas
* @date 2014-11-28 上午10:28:54
* @param newObj
* @param oldObj
* @param isNullReplace
* @throws IllegalAccessException
* @throws IllegalArgumentException
* @throws InvocationTargetException
*/
public static void objectReplace(Object newObj, Object oldObj, boolean isNullReplace) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
if (newObj != null && oldObj != null) {
Class _class1 = newObj.getClass();
Class _class2 = oldObj.getClass();
Field[] fields = _class1.getDeclaredFields();
for (Field field : fields) {
Method getMethod = getMethod(_class2, field, "get");
if (getMethod != null) {
Object value = getMethod.invoke(oldObj, null);
if (!isNullReplace && value == null) {
continue;
}
Method setMethod = getMethod(_class1, field, "set");
setMethod.invoke(newObj, value);
}
}
}
}


/**
* 兩個相同類型對象覆蓋(oldObj覆蓋newObj,isNullReplaceList裡面值為空白也需要覆蓋的欄位)

* @author jonas
* @date 2014-11-28 上午10:28:54
* @param newObj
* @param oldObj
* @param isNullReplace
* @throws IllegalAccessException
* @throws IllegalArgumentException
* @throws InvocationTargetException
*/
public static void objectReplace(Object newObj, Object oldObj, List<String> isNullReplaceList)
throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
if (newObj != null && oldObj != null) {
if (isNullReplaceList == null) {
isNullReplaceList = new ArrayList<String>();
}
Class _class1 = newObj.getClass();
Class _class2 = oldObj.getClass();
if (_class1.getName().equals(_class2.getName())) {
Field[] fields = _class1.getDeclaredFields();
for (Field field : fields) {
Method getMethod = getMethod(_class1, field, "get");
if (getMethod != null) {
Object value = getMethod.invoke(oldObj, null);
if (!isNullReplaceList.contains(field.getName()) && value == null) {
continue;
}
Method setMethod = getMethod(_class1, field, "set");
setMethod.invoke(newObj, value);
}
}
}
}
}


/**
* 將List<T>裡面對象轉換成List<Map>

* @author jonas
* @date 2014-11-28 上午10:30:17
* @param list
* @return
* @throws IllegalArgumentException
* @throws IllegalAccessException
* @throws ParseException
* @throws InvocationTargetException
*/
public static List<Map<String, Object>> listToMap(List list) throws IllegalArgumentException, IllegalAccessException, ParseException, InvocationTargetException {
List<Map<String, Object>> listMap = null;
for (Object object : list) {
if (listMap == null) {
listMap = new ArrayList<Map<String, Object>>();
}
Map<String, Object> map = objectToMap(object, null);
if (map != null && !map.isEmpty()) {
listMap.add(map);
}
}
return listMap;
}


public static Map<String, Object> objectToMap(Object object) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException, ParseException {
Class _class = object.getClass();
Field[] fields = _class.getDeclaredFields();
Map<String, Object> map = null;
for (Field field : fields) {
if (map == null) {
map = new HashMap<String, Object>();
}
Method method = getMethod(_class, field, "get");
if (method != null) {
setFieldValue(object, field, map, method, true);
}
}
return map;
}


public static void listMapValueToString(List<Map> listMap) throws IllegalArgumentException, IllegalAccessException, ParseException, InvocationTargetException {
if (listMap == null) {
return;
}
for (Map map : listMap) {
mapValueToString(map);
}
}


public static void listMapValueToStrings(List<Map<String, Object>> listMap) throws IllegalArgumentException, IllegalAccessException, ParseException, InvocationTargetException {
if (listMap == null) {
return;
}
for (Map map : listMap) {
mapValueToString(map);
}
}


public static Map<String, Object> objectToMap(Object object, List<String> ignoreFieldList) {
Class _class = object.getClass();
Field[] fields = _class.getDeclaredFields();
Map<String, Object> map = null;
for (Field field : fields) {
if (map == null) {
map = new HashMap<String, Object>();
}
String fieldName = field.getName();
if (ignoreFieldList != null && ignoreFieldList.contains(fieldName)) {
continue;
}
Method method = getMethod(_class, fieldName, "get");
if (method != null) {
try {
setFieldValue(object, field, map, method, true);
} catch (Exception e) {
e.printStackTrace();
}
}
}
return map;
}


/**
* 將List<T>裡面對象轉換成List<Map>

* @author jonas
* @date 2014-11-28 上午10:30:17
* @param list
* @return
* @throws IllegalArgumentException
* @throws IllegalAccessException
* @throws ParseException
* @throws InvocationTargetException
*/
public static List<Map<String, Object>> listToMap(List list, List<String> ignoreFieldList)
throws IllegalArgumentException, IllegalAccessException, ParseException, InvocationTargetException {
List<Map<String, Object>> listMap = null;
for (Object object : list) {
if (listMap == null) {
listMap = new ArrayList<Map<String, Object>>();
}
Map<String, Object> map = objectToMap(object, ignoreFieldList);
if (map != null && !map.isEmpty()) {
listMap.add(map);
}
}
return listMap;
}


public static void mapValueToString(Map map) {
if (map != null) {
for (Object key : map.keySet()) {
Object value = map.get(key);
if (value != null) {
map.put(key, value.toString());
}
}
}
}


public static List<Map> listToMapByMethod(List list) throws IllegalArgumentException, IllegalAccessException, ParseException, InvocationTargetException {
List<Map> listMap = null;
for (Object object : list) {
if (listMap == null) {
listMap = new ArrayList<Map>();
}
Map map = objectToMapByMethod(object, null);
if (map != null && !map.isEmpty()) {
listMap.add(map);
}
}
return listMap;
}


public static List<Map<String, Object>> listToMapByMethod(List list, List<String> ignoreFieldList)
throws IllegalArgumentException, IllegalAccessException, ParseException, InvocationTargetException {
List<Map<String, Object>> listMap = null;
for (Object object : list) {
if (listMap == null) {
listMap = new ArrayList<Map<String, Object>>();
}
Map<String, Object> map = objectToMapByMethod(object, ignoreFieldList);
if (map != null && !map.isEmpty()) {
listMap.add(map);
}
}
return listMap;
}


public static Map<String, Object> objectToMapByMethod(Object object, List<String> ignoreFieldList)
throws IllegalArgumentException, IllegalAccessException, InvocationTargetException, ParseException, SecurityException {
Class _class = object.getClass();
Method[] methods = _class.getMethods();
Map map = null;
for (Method method : methods) {
if (map == null) {
map = new HashMap();
}
String methodName = method.getName();
if (ignoreFieldList != null && ignoreFieldList.contains(methodName)) {
continue;
}
String prefix = methodName.substring(0, 3);
String suffix = methodName.substring(3, methodName.length());
if ("get".equals(prefix)) {
setFieldValue(object, suffix, map, method, true);
} else if ("set".equals(prefix)) {
Method _method = null;
try {
_method = _class.getMethod("get" + suffix, null);
} catch (NoSuchMethodException e) {
}
if (_method != null) {
setFieldValue(object, suffix, map, _method, true);
}
} else {
setFieldValue(object, methodName, map, method, true);
}
}
return map;
}


/**
* 將對象裡面的String欄位值消除空格

* @author jonas
* @date 2014-11-28 上午10:32:54
* @param object
* @return
* @throws IllegalAccessException
* @throws IllegalArgumentException
* @throws InvocationTargetException
* @throws ParseException
*/
public static Object objectFieldTrim(Object object) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, ParseException {
Class _class = object.getClass();
Field[] fields = _class.getDeclaredFields();
for (Field field : fields) {
Method method = getMethod(_class, field, "get");
Object value = method.invoke(object, null);
if (value != null) {
if (field.getType().getName().equals("java.lang.String")) {
setFieldValue(object, field, value.toString().trim());
} else {
setFieldValue(object, field, value.toString());
}
}
}
return object;
}


/**
* 擷取對象get或者set方法

* @author jonas
* @date 2014-11-28 上午10:34:56
* @param _class
* @param field
* @param prefix
* @return
*/
public static Method getMethod(Class _class, Field field, String prefix) {
Method[] methods = _class.getDeclaredMethods();
for (Method method : methods) {
String methodName = method.getName();
String fieldName = field.getName();
String _fieldName = prefix + fieldName;
if (methodName.toUpperCase().equals(_fieldName.toUpperCase())) {
return method;
}
}
return null;
}


/**
* 擷取對象get或者set方法

* @author jonas
* @date 2014-11-28 上午10:34:56
* @param _class
* @param field
* @param prefix
* @return
*/
public static Method getMethod(Class _class, String fieldName, String prefix) {
Method[] methods = _class.getDeclaredMethods();
for (Method method : methods) {
String methodName = method.getName();
String _fieldName = prefix + fieldName;
if (methodName.toUpperCase().equals(_fieldName.toUpperCase())) {
return method;
}
}
return null;
}


private static void setFieldValue(Object obj, Field field, String value) throws IllegalArgumentException, IllegalAccessException, ParseException {
field.setAccessible(true);
String fieldType = field.getType().getName();
if (fieldType.equals("java.lang.String")) {
field.set(obj, value);
} else if (fieldType.equals("java.lang.Integer") || fieldType.equals("int")) {
field.set(obj, Integer.valueOf(value));
} else if (fieldType.equals("java.lang.Long") || fieldType.equals("long")) {
field.set(obj, Long.valueOf(value));
} else if (fieldType.equals("java.lang.Float") || fieldType.equals("float")) {
field.set(obj, Float.valueOf(value));
} else if (fieldType.equals("java.lang.Double") || fieldType.equals("double")) {
field.set(obj, Double.valueOf(value));
} else if (fieldType.equals("java.util.Date")) {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
field.set(obj, df.parse(value));
} else if (fieldType.equals("java.math.BigDecimal")) {
field.set(obj, new BigDecimal(value));
} else if (fieldType.equals("java.lang.Boolean") || fieldType.equals("boolean")) {
field.set(obj, Boolean.valueOf(value));
} else if (fieldType.equals("java.lang.Byte") || fieldType.equals("byte")) {
field.set(obj, Byte.valueOf(value));
} else if (fieldType.equals("java.lang.Short") || fieldType.equals("short")) {
field.set(obj, Short.valueOf(value));
}
}


private static void setFieldValue(Object obj, Field field, Map map, Method method, boolean isLegalMethod)
throws IllegalArgumentException, IllegalAccessException, ParseException, InvocationTargetException {
field.setAccessible(true);
String fieldName = field.getName();
setFieldValue(obj, fieldName, map, method, isLegalMethod);
}


private static void setFieldValue(Object obj, String fieldName, Map map, Method method, boolean isLegalMethod)
throws IllegalArgumentException, IllegalAccessException, ParseException, InvocationTargetException {
if (map != null && map.containsKey(fieldName.toUpperCase())) {
fieldName = obj.getClass().getSimpleName() + fieldName;
}
Class[] _c = method.getParameterTypes();
Class returnCls = method.getReturnType();
if (isLegalMethod) {
if ((_c == null || _c.length == 0) && isBasicType(returnCls.getName())) {
map.put(fieldName.toUpperCase(), method.invoke(obj, null));
}
} else {
map.put(fieldName.toUpperCase(), method.invoke(obj, null));
}
}


public static boolean isBasicType(String typeName) {
if (typeName.equals("java.lang.String") || typeName.equals("java.lang.Integer") || typeName.equals("int") || typeName.equals("java.lang.Long") || typeName.equals("long")
|| typeName.equals("java.lang.Float") || typeName.equals("float") || typeName.equals("java.lang.Double") || typeName.equals("double")
|| typeName.equals("java.util.Date") || typeName.equals("java.math.BigDecimal") || typeName.equals("java.lang.Boolean") || typeName.equals("boolean")
|| typeName.equals("java.lang.Byte") || typeName.equals("byte")

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.