利用反射打印对象所有属性的工具类
package day01.util;
import java.lang.reflect.Field;
public class EntityUtil {
/**
* @throws IllegalAccessException
* @throws IllegalArgumentException
* @param一个Object对象
* @return传入参数对象的所有属性名及值
*/
public static String entityToString(Object obj) throws IllegalArgumentException, IllegalAccessException
{
Class c = obj.getClass();
if (c == null)
return null;
else
{
StringBuilder sb = new StringBuilder();
String str = getClassFields(obj, c, sb);
return str;
}
}
private static String getClassFields(Object obj, Class c, StringBuilder sb) throws IllegalArgumentException, IllegalAccessException
{
int i;
String name;
Object value;
sb.append(c.getName()).append("[");
Field[] fs = c.getDeclaredFields();
for (i=0; i<fs.length; i++)
{ //start for
fs[i].setAccessible(true);
name = fs[i].getName();
value = fs[i].get(obj);
sb.append(name).append("=").append(value);
if (i != fs.length-1)
sb.append(",");
} //end for
c = c.getSuperclass();
if (c != null && c != Object.class)
{
sb.append(" "); //父类属性前加空格
getClassFields(obj, c, sb);
}
sb.append("]");
return sb.toString();
}
}