利用java反射机制分析对象

来源:互联网 发布:网络存储器是什么 编辑:程序博客网 时间:2024/04/28 21:39

利用java反射机制查看在编译时还不清楚的对象域。


思路:

使用getDeclaredFileds获取所有的数据域;

使用setAccessible将所有的域值设置为可访问的;

对每个域获取名字和值;


代码

  类对象分析---ObjectAnalyzer

import java.lang.reflect.*;import java.util.*;/** * This program uses reflection to spy on objects. */class ObjectAnalyzer{/*--存放访问者的信息---*/private ArrayList<Object> visited = new ArrayList<Object>();/**    * 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)   {      /*------如果为空则立刻结束,返回null------*/    if (obj == null)  {      return "null";      }  /*-如果访问数组中存在obj,立刻结束,返回....-*/      if (visited.contains(obj))       {      return "...";      }      visited.add(obj);                 Class<?> cl = obj.getClass();      /*---如果obj为字符串则立刻结束,返回String--*/      if (cl == String.class)       {      return (String) obj;       }          /*---------如果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 + "}";      }      /*---------如果obj为非数组,处理-----------*/      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;   }}

  自定义的类--Demo

public class Demo{private String name;private int   age;public  Demo(String name, int age){this.name = name;this.age  = age;}public String toString(){return new ObjectAnalyzer().toString(this);}}

  测试端---ObjectAnalyzerTest

public class ObjectAnalyzerTest{   public static void main(String[] args)   {   Demo demo = new Demo("wei",24);   System.out.println(demo.toString());   }}

测试结果


0 0
原创粉丝点击