/**
   @version 1.00 1998-04-11
   @author Cay Horstmann
*/
//import corejava.*;
import java.lang.reflect.*;
import java.util.*;



class ObjectAnalyzer
{
   /**
      Converts an object 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 static String toString(Object obj)
   {  
      Class cl = obj.getClass();
      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];
            r += f.getName() + "=";
            try
            {  
               Object val = f.get(obj);
               r += val.toString();
            } 
            catch (Exception e) { e.printStackTrace(); }
            if (i < fields.length - 1)
               r += ",";
         }
         r += "]";
         cl = cl.getSuperclass();
      }
      while (cl != Object.class);

      return r;
   }

   /**
      Tests whether two objects are equal by checking if all
      field values are equal
      @param a an object
      @param b another object
      @return true if a and b are equal
   */
   public static boolean equals(Object a, Object b)
   {  
      if (a == b) return true;
      if (a == null || b == null) return false;
      Class cl = a.getClass();
      if (cl != b.getClass()) return false;

      // inspect the fields of this class and all superclasses
      do
      {
         Field[] fields = cl.getDeclaredFields();
         AccessibleObject.setAccessible(fields, true);
         for (int i = 0; i < fields.length; i++)
         {  
            Field f = fields[i];
            // if field values don't match, objects aren't equal
            try
            {  
               if (!f.get(a).equals(f.get(b)))
                  return false;
            }
            catch (Exception e) { e.printStackTrace(); }
         }
         cl = cl.getSuperclass();
      }
      while (cl != Object.class);

      return true;
   }
}

