zoukankan      html  css  js  c++  java
  • 在运行中使用反射分析对象

    简介

    是一种调试手段 要设定权限 就能访问运行中对象 private 域中的东西了

    code

    package com;
    
    import java.lang.reflect.AccessibleObject;
    import java.lang.reflect.Array;
    import java.lang.reflect.Field;
    import java.lang.reflect.Modifier;
    import java.util.ArrayList;
    
    public class ObjectAnalyzer {
    	private ArrayList<Object> visited = new ArrayList<>();
    	
    	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()) {
    			System.out.println("[debug]" + cl.getComponentType() + "[debug]");
    			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; // 判断是否是原始类型 比如 int
    				else r += toString(val);
    			}
    			return r + "}";
    		}
    		
    		String r = cl.getName();
    		do{
    			r += "[";
    			Field[] fields = cl.getDeclaredFields();
    			AccessibleObject.setAccessible(fields, true); // 设定访问权限
    			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;
    	}
    }
    
    
    package com;
    import java.util.ArrayList;
    public class ObjectAnalyzerTest {
    	public static void main(String[] args){
    		ArrayList<Integer> squares = new ArrayList<>();
    		for(int i=1; i<=5; i++) {
    			squares.add(i * i);
    		}
    		System.out.println(new ObjectAnalyzer().toString(squares));
    	}
    }
    
    

    answer

    [debug]class java.lang.Object[debug]
    java.util.ArrayList[elementData=class java.lang.Object[]{java.lang.Integer[value=1][][],java.lang.Integer[value=4][][],java.lang.Integer[value=9][][],java.lang.Integer[value=16][][],java.lang.Integer[value=25][][],null,null,null,null,null},size=5][modCount=5][][]
    
    
    Hope is a good thing,maybe the best of things,and no good thing ever dies.----------- Andy Dufresne
  • 相关阅读:
    Hadoop之HDFS的热备份
    Hadoop之联邦HDFS
    Hadoop之HDFS如何保证高可用
    Hadoop之HDFS的读流程
    Hadoop之HDFS数据写流程和写失败的情况
    Hadoop之HDFS的block、packet、chunk
    Hadoop之HDFS的元数据冷备份(CheckPoint)
    当ZooKeeper作为Dubbo的注册中心的时候,是怎么工作的?
    Dubbo
    mysql磁盘满了如何恢复
  • 原文地址:https://www.cnblogs.com/eat-too-much/p/13407260.html
Copyright © 2011-2022 走看看