java反射之ObjectAnalyzer
JAVA2中关于反射的应用主要是用来分析类结构,其中的Field,Method,Constructor类分别描述类的字段,方法和构造器。它们又分别读有相应的getName,getType,getModifiers等方法来返回其类信息。
类ObjectAnalyzerTest:
package cn.lesorb;import java.text.NumberFormat;import java.util.ArrayList;public class ObjectAnalyzerTest {public static void main(String[] args) {ObjectAnalyzer objAnalyzer = new ObjectAnalyzer();Object obj = NumberFormat.getCurrencyInstance();System.out.println(objAnalyzer.toString(obj));ArrayList<Object> al = objAnalyzer.visited;for(int i=0;i<al.size();i++) {System.out.println(al.get(i));}}}import java.lang.reflect.AccessibleObject;import java.lang.reflect.Array;import java.lang.reflect.Field;import java.lang.reflect.Modifier;import java.util.ArrayList;class ObjectAnalyzer{@SuppressWarnings("unchecked")public String toString(Object obj){/***Converts an object to a string representation that lists all fields**/if(obj==null) return "null"; if(visited.contains(obj)) return "..."; visited.add(obj);Class c1=obj.getClass();if(c1==String.class){return (String)obj;}if(c1.isArray()){String r=c1.getComponentType()+"[]{"; for(int i=0;i<Array.getLength(obj);i++){ if(i>0){ r+=","; } Object val=Array.get(obj,i); if(c1.getComponentType().isPrimitive()){ r+=val; } else{ r+=toString(val); } }return r+"}"; } String r=c1.getName(); do{ r+="["; Field[] fields=c1.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+="]"; c1=c1.getSuperclass(); } while(c1!=null); return r; }ArrayList<Object> visited=new ArrayList<Object>();}