日期:2014-05-20 浏览次数:20741 次
public String toString(Object obj)
{
if(obj == null)
return "null";
if(visted.contains(obj))
return "...";
visted.add(obj);
Class c = obj.getClass();
if(c == String.class)
return (String)obj;
if(c.isArray())
{
String arr = c.getComponentType() + "[]{";
for (int i = 0; i < Array.getLength(obj); i++)
{
if(i > 0)
arr += ",";
Object val = Array.get(obj , i);
if(c.getComponentType().isPrimitive())
arr += val;
else
arr += toString(val);
}
return arr + "}";
}
String r = c.getName();
do
{
r += "{";
Field[] fields = c.getDeclaredFields();
AccessibleObject.setAccessible(fields , true);
for (Field f : fields)
{
if(!Modifier.isStatic(f.getModifiers()))
{
if(!r.endsWith("["))
r += ",";
try
{
Class<?> c1 = f.getType();
Object val = f.get(obj);
if(c1.isPrimitive())
r += val;
//这是怎么执行的 debug看 继续for循环 为什么没重新进toString方法
else
r += toString(val);
}
catch (IllegalArgumentException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IllegalAccessException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
r += "]";
c = c.getSuperclass();
}
while (c != null);
return r;
}
private ArrayList<Object> visted = new ArrayList<Object>();
for (int i = 0; i < Array.getLength(obj); i++)
{
if(i > 0)
arr += ",";
Object val = Array.get(obj , i);
if(c.getComponentType().isPrimitive()){
arr += val;
}else{
arr += toString(val);
}
}