import java.lang.reflect.*;
import java.util.*;
import java.text.*;public class ObjectAnalyzerTest
{
public static void main(String[] args)
{
Object obj=new String();
System.out.println(new ObjectAnalyzer().toString(obj));
}
}class ObjectAnalyzer
{
/**
Converts an lbject to a string representation that lists all fields.
@param obj an object
@return a string with the object's class name and all field names and values
*/
public String toString(Object obj)
{
if (obj==null)return "null"; if (visited==null)
{
Object first=new Object();
first=obj;
visited.add(first);
}
else
{
if (visited.contains(obj))return "...";
if (obj instanceof first.getClass()) visited.add(obj);
else System.exit(0);
}
Class cl=obj.getClass();
if(cl==String.class)return (String)obj;
if(cl.isArray())
{
String r=cl.getComponentType()+"[]{";
for(int i=0;i<Array.getLength(obj);i++)
{
if(i>0)r+=",";
Object val=Array.get(obj,i);
if(cl.getComponentType().isPrimitive())r+=val;
else r+=toString(val);
}
return r+"}";
} String r=cl.getName();
//inspect the fields of this class and all superclasses
do
{
r+="{";
Field[] fields=cl.getDeclaredFields();
AccessibleObject.setAccessible(fields,true);
//get the names and values of all fields
for(int i=0;i<fields.length;i++)
{
Field f=fields[i];
if(!Modifier.isStatic(f.getModifiers()))
{
if(!r.endsWith("["))r+=",";
r+=f.getName()+"=";
try
{
Class t=f.getType();
Object val=f.get(obj);
if(t.isPrimitive())r+=val;
else r+=toString(val);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
r+="]";
cl=cl.getSuperclass();
}
while(cl!=Object.class); return r;
} private ArrayList visited=new ArrayList();
}
为什么结果会这样:ObjectAnalyzerTest.java:34: 需要 ')'
if (obj instanceof first.getClass()) visited.add(obj);
                                                         ^
1 错误工具以退出代码 1 完成
要如何才改正,getClass()括号是配对了的呀,为什么还需要“)”

解决方案 »

  1.   

    if (visited==null)
    {
    Object first=new Object();
    ......
    }
    else
    {
    .....
    if (obj instanceof first.getClass()) visited.add(obj);
    ....
    }
    first 在else里是访问不到的
      

  2.   

    Object first=new Object();first定义在if判断之前
      

  3.   

    那如果我不用first,而直接使用visited.get(0)
    把这段代码改为:
    if (visited==null)
    {
         visited.add(obj);
    }
    else
    {
         .....
         if (obj instanceof visited.get(0).getClass()) visited.add(obj);
         ....
    }
    以后,这个结果仍然不变
      

  4.   

    if (visited==null)
    {
    visited.add(obj);
    }
    else
    {
    .....
    if (obj instanceof ArrayList) visited.add(obj);
    ....
    }
      

  5.   

    instanceof第二个参数不是需要一个类吗?visited.get(0).getClass()为什么不行呢?
      

  6.   

    if (obj instanceof Object)
    建议将换成一个具体的类型
    我估计应该就是instanceof的问题,他应该需要的是一个具体的类型
    继续等待
      

  7.   

    可是我想把visited的第一个元素存入first,然后再判断以后的元素是否是该元素的同类或其子类,如果是则加入,否则则不加
      

  8.   

    测试了一下,即便
    if(true)
    {
    }
    编译仍然出错,提示 :注意:ObjectAnalyzerTest.java 使用了未经检查或不安全的操作。
                         注意:要了解详细信息,请使用 -Xlint:unchecked 重新编译。
    呵呵,编码不规范,可读性比较差啦,根据你的设计思路再改改吧。
    if(obj instanceof first.getClass())
    getClass()返回一个运行时的类,是没错的,但是如果obj和first.getClass()处于不同继承体编译就会出错。
    改为 if (first.getClass().isInstance(obj)) 或者if (first.equals(obj)) 都可以比较fist和obj是不是属于同种类型。
    下面是我对getClass()的测试
     class TestClassName
     {
     
         public static void main(String arg[])
        {
          TestClassName  obj=new TestClassName();
                         obj.printClassName(obj) ;
           Object first =new Object();
           System.out.println("The class of " + first+
                                " is " + first.getClass().getName());
           Object obj =new Object();      
           //if(obj instanceof first.getClass())
           //System.out.println("true");
        
        }
        
         void printClassName(Object obj) 
        {
             System.out.println("The class of " + obj +
                                " is " + obj.getClass().getName());
         }
    }
    输出:
    The class of TestClassName@35ce36 is TestClassName
    The class of java.lang.Object@757aef is java.lang.Object
      

  9.   

    core java v1里的程序好像没有出问题的那几句
     1. import java.lang.reflect.*;
     2. import java.util.*;
     3. import java.text.*;
     4.
     5. public class ObjectAnalyzerTest
     6. {
     7.    public static void main(String[] args)
     8.    {
     9.       ArrayList<Integer> squares = new ArrayList<Integer>();
    10.       for (int i = 1; i <= 5; i++) squares.add(i * i);
    11.       System.out.println(new ObjectAnalyzer().toString(squares));
    12.    }
    13. }
    14.
    15. class ObjectAnalyzer
    16. {
    17.    /**
    18.       Converts an object to a string representation that lists
    19.       all fields.
    20.       @param obj an object
    21.       @return a string with the object's class name and all
    22.       field names and values
    23.    */
    24.    public String toString(Object obj)
    25.    {
    26.       if (obj == null) return "null";
    27.       if (visited.contains(obj)) return "...";
    28.       visited.add(obj);
    29.       Class cl = obj.getClass();
    30.       if (cl == String.class) return (String) obj;
    31.       if (cl.isArray())
    32.       {
    33.          String r = cl.getComponentType() + "[]{";
    34.          for (int i = 0; i < Array.getLength(obj); i++)
    35.          {
    36.             if (i > 0) r += ",";
    37.             Object val = Array.get(obj, i);
    38.             if (cl.getComponentType().isPrimitive()) r += val;
    39.             else r += toString(val);
    40.          }
    41.          return r + "}";
    42.       }
    43.
    44.       String r = cl.getName();
    45.       // inspect the fields of this class and all superclasses
    46.       do
    47.       {
    48.          r += "[";
    49.          Field[] fields = cl.getDeclaredFields();
    50.          AccessibleObject.setAccessible(fields, true);
    51.          // get the names and values of all fields
    52.          for (Field f : fields)
    53.          {
    54.             if (!Modifier.isStatic(f.getModifiers()))
    55.             {
    56.                if (!r.endsWith("[")) r += ",";
    57.                r += f.getName() + "=";
    58.                try
    59.                {
    60.                   Class t = f.getType();
    61.                   Object val = f.get(obj);
    62.                   if (t.isPrimitive()) r += val;
    63.                   else r += toString(val);
    64.                }
    65.                catch (Exception e) { e.printStackTrace(); }
    66.             }
    67.          }
    68.          r += "]";
    69.          cl = cl.getSuperclass();
    70.       }
    71.       while (cl != null);
    72.
    73.       return r;
    74.    }
    75.
    76.    private ArrayList<Object> visited = new ArrayList<Object>();
    77. }
      

  10.   

    if (visited==null)
    {
    Object first=new Object();
    first=obj;
    visited.add(first);
    }
    visited 都null了怎么可能还visited.add(first);
      

  11.   

    卡西兄,ArrayList是一个元素不固定的数组列表,正因为刚开始还没有元素,所以才要用ArrayList.add(Object)来加入元素呀,在还没有元素的时候难道不是null吗?
      

  12.   


    list没有元素并不代表其值为null。