使用Java反射机制将Bean对象转换成Map(驼峰命名方式 — 下划线命名方式)

1、驼峰与下划线方式名称互相转换工具类

public class CamelUnderlineUtil {

	private static final char UNDERLINE ='_';
	public static String camelToUnderline(String param) {
		if (StringUtil.isEmpty(param)) {
			return "";
		}
		StringBuilder sb = new StringBuilder();
		int len = param.length();
		for (int i = 0; i < len; i++) {
			char c = param.charAt(i);
			if (Character.isUpperCase(c)) {
				sb.append(UNDERLINE);
				sb.append(Character.toLowerCase(c));
			} else {
				sb.append(c);
			}
		}
		return sb.toString();
	}
	
	public static String underlineToCamel(String param){
		if (StringUtil.isEmpty(param)) {
			return "";
		}
		StringBuilder sb = new StringBuilder();
		int len = param.length();
		for (int i = 0; i < len; i++) {
			char c = param.charAt(i);
			if (c==UNDERLINE) {
				if(++i

2、Bean对象转Map方法

private Map convertObjectToMap(Object obj, Class clazz) throws Exception {
		Map dstMap = new HashMap();
		Field[] fields = obj.getClass().getDeclaredFields();
		for (Field field : fields) {
			if ("serialVersionUID".equals(field.getName())) {
				continue;
			}

			String dstName = CamelUnderlineUtil.camelToUnderline(field.getName());
			PropertyDescriptor pd;
			pd = new PropertyDescriptor(field.getName(), clazz);
			Method method = pd.getReadMethod();
			Object dstObject = method.invoke(obj);
			if (dstObject instanceof Date) {
				dstObject = convertToTimeStamp16((Date) dstObject);
			}
			if (dstObject instanceof ArrayList) {
				dstObject = "";
			}
			dstMap.put(dstName, StringUtil.isEmpty(dstObject) ? "" : dstObject.toString());
		}
		return dstMap;
	}

 

你可能感兴趣的:(java)