Java 반사 분석 개체의 Fields

14104 단어 java 핵심 기술
package chapter05.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;

public class ObjectAnalyzer {
	private ArrayList 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()){							
			  String r=cl.getComponentType()+"[]{"; 
			  for(int i=0;i0)r+=",";
				  Object val=Array.get(obj, i);
				  if(cl.getComponentType().isPrimitive()){
					  r+=val;
				  }
				  else{
					  r+=toString(val);                            //!!!
				  }
			  }
			  return r+"};";
		}
		String r=cl.getName();
		do{
			r+="[";
			Field[] fields=cl.getDeclaredFields();            
			AccessibleObject.setAccessible(fields, true);    
			for(Field element:fields){
				if(!Modifier.isStatic(element.getModifiers())){
					if(!r.endsWith("["))r+=",";
					r+=element.getName()+"=";
					try{
						Class t=element.getType();              
						Object val=element.get(obj);            
						if(t.isPrimitive())r+=val;
						else r+=toString(val);                  //!!!
					}catch(Exception e){
						e.printStackTrace();
					}
				}
			}
			r+="]";
			cl.getSuperclass();
		}while(cl!=null);
		return r;
	}
}

재단 테스트
package chapter05.ObjectAnalyzer;

import java.util.ArrayList;

public class ObjectAnalyzerTest {
	public static void main(String[] args){
		ArrayList squares=new ArrayList<>();
		for(int i=1;i<=5;i++){
			squares.add(i*i);
		}
		System.out.println(new ObjectAnalyzer().toString(squares));
	}
}
이것은 코어Java에서 반사 분석을 이용한 기본 유형 수조와 기본 유형 일반 수조에 대한 코드이다. 먼저 몇 가지 문제를 명확히 하자.
1. 범용수조는 수조가 아니다. 2.자기가 만든 클래스, 수조를 만든 후, 수조,
다음과 같습니다.
ArrayList squares=new ArrayList<>();
		for(int i=1;i<=5;i++){
			squares.add(i*i);
		}
		System.out.println(squares.getClass().isArray());// false

		Employee[] xy=new Employee[2];
		Employee x=new Employee("asan",35000.0);
		Employee y=new Employee("asi",45000.0);
		System.out.println(xy.getClass().isArray()); // true

그런 다음 정리합니다.
				  if(cl.getComponentType().isPrimitive()){
					  r+=val;
				  }
				  else{
					  r+=toString(val);// 
				  
						if(t.isPrimitive())r+=val;
						else r+=toString(val); 
첫 번째는 수조가 기본 형식이라면 안에 있는 요소를 일일이 인쇄하고 그렇지 않으면null로 되돌려준다는 것이다. (내가 이해한 바에 의하면 수조가 기본 데이터 형식이나String 형식이 아니라면 수조 요소가null로 되돌려준다면 이 대상 분석기는 너무 약한 거 아니야?)
두 번째는 첫 번째와 다릅니다. 예를 들어 반환된 결과는 다음과 같습니다.
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][][]

 
if(!r.endsWith("["))r+=",";
 
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][][]

 else , :
java.util.ArrayList[elementData=,size=5][modCount=5][][]

 if :
java.util.ArrayList[elementData=class java.lang.Object[]{java.lang.Integer[value=,,,][][],java.lang.Integer[value=,,,][][],java.lang.Integer[value=,,,][][],java.lang.Integer[value=,,,][][],java.lang.Integer[value=,,,][][],null,null,null,null,null};,size=java.lang.Integer[value=,,,][][]][modCount=,,,][][]

됐다
뒤에 세 개의 [][]를 따라 이해하기 쉽다. 즉,Array List에는 모두 세 개의 슈퍼클래스가 있다. 이 범주 그룹 중 첫 번째 슈퍼클래스, 그 중에는mod Count의 Field가 있다. 이 Field name은mod Count이다. 이 범주 그룹이 수정된 횟수를 가리킨다!
문제는 다음과 같습니다.
else를 제거한 후 비기본 데이터 형식에 대한Feild의 설명이 없는 것을 발견했습니다.그러면if의 지점은 두 개의 5를 인쇄하는 것입니까?아니란 걸 알 수 있다. 우리가if분지를 제거한 후에 모든 기본 데이터 유형이 없어진 것을 발견했다. 이 점은 설명할 수 없다???
쉼표를 제거한 후 중괄호 안에 하나만 더 많아졌다.즉, Array List squares라는 범주형 수조는 두 개의 Field가 있는데 하나는 요소이고 다른 하나는size이다.API에서는 이 점을 찾을 수 없습니다???
다시 벗겨볼게요.
if(!Modifier.isStatic(element.getModifiers())){

다음과 같은 결과를 얻습니다.
java.util.ArrayList[serialVersionUID=8683452581122892189,DEFAULT_CAPACITY=10,EMPTY_ELEMENTDATA=class java.lang.Object[]{};,elementData=class java.lang.Object[]{java.lang.Integer[MIN_VALUE=-2147483648,MAX_VALUE=2147483647,TYPE=java.lang.Class[ANNOTATION=8192,ENUM=16384,SYNTHETIC=4096,cachedConstructor=null,newInstanceCallerCache=null,name=null,allPermDomain=null,useCaches=true,declaredFields=null,publicFields=null,declaredMethods=null,publicMethods=null,declaredConstructors=null,publicConstructors=null,declaredPublicFields=null,declaredPublicMethods=null,classRedefinedCount=0,lastRedefinedCount=0,genericInfo=null,serialVersionUID=3206093459760846163,serialPersistentFields=class java.io.ObjectStreamField[]{};,reflectionFactory=sun.reflect.ReflectionFactory[initted=true,reflectionFactoryAccessPerm=java.lang.RuntimePermission[serialVersionUID=7399184964622342223][serialVersionUID=6279438298436773498,wildcard=false,path=reflectionFactoryAccess,exitVM=false][serialVersionUID=-5636570222231596674,name=,,,][],soleInstance=,,,,langReflectAccess=java.lang.reflect.ReflectAccess[][],noInflation=false,inflationThreshold=15][],initted=true,enumConstants=null,enumConstantDirectory=null,annotations=null,declaredAnnotations=null,annotationType=null,classValueMap=null][],digits=char[]{0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z};,DigitTens=char[]{0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,3,4,4,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,6,6,6,6,6,6,6,6,6,6,7,7,7,7,7,7,7,7,7,7,8,8,8,8,8,8,8,8,8,8,9,9,9,9,9,9,9,9,9,9};,DigitOnes=char[]{0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9};,sizeTable=int[]{9,99,999,9999,99999,999999,9999999,99999999,999999999,2147483647};,value=1,SIZE=32,serialVersionUID=1360826667806852920,$assertionsDisabled=true][serialVersionUID=-8742448824652078965][],java.lang.Integer[MIN_VALUE=-2147483648,MAX_VALUE=2147483647,TYPE=java.lang.Class[ANNOTATION=8192,ENUM=16384,SYNTHETIC=4096,cachedConstructor=null,newInstanceCallerCache=null,name=int,allPermDomain=null,useCaches=true,declaredFields=null,publicFields=null,declaredMethods=null,publicMethods=null,declaredConstructors=null,publicConstructors=null,declaredPublicFields=null,declaredPublicMethods=null,classRedefinedCount=0,lastRedefinedCount=0,genericInfo=null,serialVersionUID=3206093459760846163,serialPersistentFields=class java.io.ObjectStreamField[]{};,reflectionFactory=sun.reflect.ReflectionFactory[initted=true,reflectionFactoryAccessPerm=java.lang.RuntimePermission[serialVersionUID=7399184964622342223][serialVersionUID=6279438298436773498,wildcard=false,path=reflectionFactoryAccess,exitVM=false][serialVersionUID=-5636570222231596674,name=,,,][],soleInstance=,,,,langReflectAccess=java.lang.reflect.ReflectAccess[][],noInflation=false,inflationThreshold=15][],initted=true,enumConstants=null,enumConstantDirectory=null,annotations=null,declaredAnnotations=null,annotationType=null,classValueMap=null][],digits=char[]{0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z};,DigitTens=char[]{0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,3,4,4,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,6,6,6,6,6,6,6,6,6,6,7,7,7,7,7,7,7,7,7,7,8,8,8,8,8,8,8,8,8,8,9,9,9,9,9,9,9,9,9,9};,DigitOnes=char[]{0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9};,sizeTable=int[]{9,99,999,9999,99999,999999,9999999,99999999,999999999,2147483647};,value=4,SIZE=32,serialVersionUID=1360826667806852920,$assertionsDisabled=true][serialVersionUID=-8742448824652078965][],java.lang.Integer[MIN_VALUE=-2147483648,MAX_VALUE=2147483647,TYPE=java.lang.Class[ANNOTATION=8192,ENUM=16384,SYNTHETIC=4096,cachedConstructor=null,newInstanceCallerCache=null,name=int,allPermDomain=null,useCaches=true,declaredFields=null,publicFields=null,declaredMethods=null,publicMethods=null,declaredConstructors=null,publicConstructors=null,declaredPublicFields=null,declaredPublicMethods=null,classRedefinedCount=0,lastRedefinedCount=0,genericInfo=null,serialVersionUID=3206093459760846163,serialPersistentFields=class java.io.ObjectStreamField[]{};,reflectionFactory=sun.reflect.ReflectionFactory[initted=true,reflectionFactoryAccessPerm=java.lang.RuntimePermission[serialVersionUID=7399184964622342223][serialVersionUID=6279438298436773498,wildcard=false,path=reflectionFactoryAccess,exitVM=false][serialVersionUID=-5636570222231596674,name=,,,][],soleInstance=,,,,langReflectAccess=java.lang.reflect.ReflectAccess[][],noInflation=false,inflationThreshold=15][],initted=true,enumConstants=null,enumConstantDirectory=null,annotations=null,declaredAnnotations=null,annotationType=null,classValueMap=null][],digits=char[]{0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z};,DigitTens=char[]{0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,3,4,4,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,6,6,6,6,6,6,6,6,6,6,7,7,7,7,7,7,7,7,7,7,8,8,8,8,8,8,8,8,8,8,9,9,9,9,9,9,9,9,9,9};,DigitOnes=char[]{0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9};,sizeTable=int[]{9,99,999,9999,99999,999999,9999999,99999999,999999999,2147483647};,value=9,SIZE=32,serialVersionUID=1360826667806852920,$assertionsDisabled=true][serialVersionUID=-8742448824652078965][],java.lang.Integer[MIN_VALUE=-2147483648,MAX_VALUE=2147483647,TYPE=java.lang.Class[ANNOTATION=8192,ENUM=16384,SYNTHETIC=4096,cachedConstructor=null,newInstanceCallerCache=null,name=int,allPermDomain=null,useCaches=true,declaredFields=null,publicFields=null,declaredMethods=null,publicMethods=null,declaredConstructors=null,publicConstructors=null,declaredPublicFields=null,declaredPublicMethods=null,classRedefinedCount=0,lastRedefinedCount=0,genericInfo=null,serialVersionUID=3206093459760846163,serialPersistentFields=class java.io.ObjectStreamField[]{};,reflectionFactory=sun.reflect.ReflectionFactory[initted=true,reflectionFactoryAccessPerm=java.lang.RuntimePermission[serialVersionUID=7399184964622342223][serialVersionUID=6279438298436773498,wildcard=false,path=reflectionFactoryAccess,exitVM=false][serialVersionUID=-5636570222231596674,name=,,,][],soleInstance=,,,,langReflectAccess=java.lang.reflect.ReflectAccess[][],noInflation=false,inflationThreshold=15][],initted=true,enumConstants=null,enumConstantDirectory=null,annotations=null,declaredAnnotations=null,annotationType=null,classValueMap=null][],digits=char[]{0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z};,DigitTens=char[]{0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,3,4,4,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,6,6,6,6,6,6,6,6,6,6,7,7,7,7,7,7,7,7,7,7,8,8,8,8,8,8,8,8,8,8,9,9,9,9,9,9,9,9,9,9};,DigitOnes=char[]{0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9};,sizeTable=int[]{9,99,999,9999,99999,999999,9999999,99999999,999999999,2147483647};,value=16,SIZE=32,serialVersionUID=1360826667806852920,$assertionsDisabled=true][serialVersionUID=-8742448824652078965][],java.lang.Integer[MIN_VALUE=-2147483648,MAX_VALUE=2147483647,TYPE=java.lang.Class[ANNOTATION=8192,ENUM=16384,SYNTHETIC=4096,cachedConstructor=null,newInstanceCallerCache=null,name=int,allPermDomain=null,useCaches=true,declaredFields=null,publicFields=null,declaredMethods=null,publicMethods=null,declaredConstructors=null,publicConstructors=null,declaredPublicFields=null,declaredPublicMethods=null,classRedefinedCount=0,lastRedefinedCount=0,genericInfo=null,serialVersionUID=3206093459760846163,serialPersistentFields=class java.io.ObjectStreamField[]{};,reflectionFactory=sun.reflect.ReflectionFactory[initted=true,reflectionFactoryAccessPerm=java.lang.RuntimePermission[serialVersionUID=7399184964622342223][serialVersionUID=6279438298436773498,wildcard=false,path=reflectionFactoryAccess,exitVM=false][serialVersionUID=-5636570222231596674,name=,,,][],soleInstance=,,,,langReflectAccess=java.lang.reflect.ReflectAccess[][],noInflation=false,inflationThreshold=15][],initted=true,enumConstants=null,enumConstantDirectory=null,annotations=null,declaredAnnotations=null,annotationType=null,classValueMap=null][],digits=char[]{0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z};,DigitTens=char[]{0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,3,4,4,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,6,6,6,6,6,6,6,6,6,6,7,7,7,7,7,7,7,7,7,7,8,8,8,8,8,8,8,8,8,8,9,9,9,9,9,9,9,9,9,9};,DigitOnes=char[]{0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9};,sizeTable=int[]{9,99,999,9999,99999,999999,9999999,99999999,999999999,2147483647};,value=25,SIZE=32,serialVersionUID=1360826667806852920,$assertionsDisabled=true][serialVersionUID=-8742448824652078965][],null,null,null,null,null};,size=5,MAX_ARRAY_SIZE=2147483639][modCount=5][MAX_ARRAY_SIZE=2147483639][]

문제가 커졌어요. 정적 Field가 많이 생겼어요.
그런데 저희가 API 문서에서 흔적을 전혀 못 찾겠어요???

좋은 웹페이지 즐겨찾기