This program uses reflection to spy on objects : Class « Reflection « Java






This program uses reflection to spy on objects

   
/*
 This program is a part of the companion code for Core Java 8th ed.
 (http://horstmann.com/corejava)

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;

/**
 * This program uses reflection to spy on objects.
 * 
 * @version 1.11 2004-02-21
 * @author Cay Horstmann
 */
public class ObjectAnalyzerTest {
  public static void main(String[] args) {
    ArrayList<Integer> squares = new ArrayList<Integer>();
    for (int i = 1; i <= 5; i++)
      squares.add(i * i);
    System.out.println(new ObjectAnalyzer().toString(squares));
  }
}

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 String toString(Object obj) {
    if (obj == null)
      return "null";
    if (visited.contains(obj))
      return "...";
    visited.add(obj);
    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 (Field f : fields) {
        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 != null);

    return r;
  }

  private ArrayList<Object> visited = new ArrayList<Object>();
}

   
    
    
  








Related examples in the same category

1.Class Reflection: class modifierClass Reflection: class modifier
2.Class Reflection: class nameClass Reflection: class name
3.Class Reflection: name for super classClass Reflection: name for super class
4.Object Reflection: create new instance
5.Class reflectionClass reflection
6.This class shows using Reflection to get a field from another classThis class shows using Reflection to get a field from another class
7.Show the class keyword and getClass() method in actionShow the class keyword and getClass() method in action
8.Simple Demonstration of a ClassLoader WILL NOT COMPILE OUT OF THE BOX
9.Demonstrate classFor to create an instance of an object
10.CrossRef prints a cross-reference about all classes named in argv
11.Make up a compilable version of a given Sun or other API
12.Show a couple of things you can do with a Class object
13.Reflect1 shows the information about the class named in argv
14.Show that you can, in fact, take the class of a primitive
15.JavaP prints structural information about classes
16.Provides a set of static methods that extend the Java metaobject
17.Demonstration of speed of reflexive versus programmatic invocation
18.Use reflection to get console char set
19.Load the class source location from Class.getResource()
20.Access the enclosing class from an inner class
21.Use reflection to dynamically discover the capabilities of a class.
22.Get the class By way of a string
23.Get the class By way of .class
24.Return a String representation of an object's overall identity
25.Manipulate Java class files in strange and mysterious ways
26.Class file reader for obtaining the parameter names for declared methods in a class
27.Convert a given String into the appropriate Class.
28.Manipulate Java classes
29.Encapsulates a class serialVersionUID and codebase.
30.Dump a class using Reflection
31.This program uses reflection to print all features of a classThis program uses reflection to print all features of a class
32.Get Unqualified Name
33.Return a paranthesis enclosed, comma sepearated String of all SimpleClass names in params.
34.Adds the class SimpleNames, comma sepearated and surrounded by paranthesis to the call StringBuffer
35.Class Finder