简介

是一种调试手段 要设定权限 就能访问运行中对象 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][][]

posted on 2020-07-30 23:27  HDU李少帅  阅读(141)  评论(0编辑  收藏  举报