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 al = objAnalyzer.visited;
		for(int i=0;i 
 
类ObjectAnalyzer:
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;i0){
	    	 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 visited=new ArrayList();
	
} 
 
打印输出:
java.text.DecimalFormat@774c1
0
[C@156ee8e
HALF_EVEN
HALF_EVEN


-¥

'-'¤
java.text.DecimalFormatSymbols@1073a

?
CNY
E
zh_CN
zh
CN
CNY

你可能感兴趣的:(Java,F#)