1.利用java反射,根据User实体,来获取get方法中的字段值
package com.citic.gatz.utils.util;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import com.citic.gatz.utils.Stringutil;
/**
* 关于Moder工具类
*
* @author fengchao
*
*/
public class ModerUtils {
public static String getToString(Object obj) {
String result = "";
Field[] fields = obj.getClass().getDeclaredFields();
StringBuffer strBuf = new StringBuffer();
strBuf.append(obj.getClass().getName());
strBuf.append("(");
for (int i = 0; i < fields.length; i++) {
Field fd = fields[i];
try {
Method method = obj.getClass().getMethod("get" + toUpperCaseFirstOne(fd.getName()));
if(method.invoke(obj) != null) {
strBuf.append(fd.getName() + ":");
strBuf.append(method.invoke(obj) + ",");
}
} catch (NoSuchMethodException e) {
//TODO
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
try {
result = removeSuffix(strBuf.toString(), ",");
} catch (Exception e) {
e.printStackTrace();
}
return result + ")";
}
//*******************************以下方法是StringUtils中的方法**************************************
/**
* 删除字符串后面指定的后缀
* @param str
* @param suffix
* @return
* @throws Exception
*/
public static String removeSuffix(String str, String suffix)
throws Exception {
if (null == str)
return null;
if ("".equals(str.trim()))
return "";
if (null == suffix || "".equals(suffix))
return str;
if (str.endsWith(suffix)) {
return str.substring(0, str.length() - suffix.length());
}
throw new Exception(str + " 没有按指定字符串" + suffix + "结尾");
}
/**
* 字符串首字母转为大写
* @param s
* @return
*/
public static String toUpperCaseFirstOne(String s) {
if (Character.isUpperCase(s.charAt(0)))
return s;
else
return (new StringBuilder()).append(Character.toUpperCase(s.charAt(0))).append(s.substring(1)).toString();
}
}