无聊回忆下java反射

将指定类下的声明全部实例化。

 

A.java

 

package com.limaoyuan.reflection;

public class A {
	private B b;
	private C c;
	
	public C getC() {
		return c;
	}

	public void setC(C c) {
		this.c = c;
	}

	public B getB() {
		return b;
	}

	public void setB(B b) {
		this.b = b;
	}
	
}

 

 

B.java

 

package com.limaoyuan.reflection;

public class B {
}

 

C.java

 

package com.limaoyuan.reflection;

public class C {

}

 

Main.java

 

package com.limaoyuan.reflection;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Main {
	private A a ;
	private B b;
	private List<A> aList;
	private Map map;
	private HashMap hashmap;
	
	public A getA() {
		return a;
	}
	public void setA(A a) {
		this.a = a;
	}
	public B getB() {
		return b;
	}
	public void setB(B b) {
		this.b = b;
	}
	
	public List<A> getaList() {
		return aList;
	}
	public void setaList(List<A> aList) {
		this.aList = aList;
	}
	
	
	
	public HashMap getHashmap() {
		return hashmap;
	}
	public void setHashmap(HashMap hashmap) {
		this.hashmap = hashmap;
	}
	public Map getMap() {
		return map;
	}
	public void setMap(Map map) {
		this.map = map;
	}
	public void ins() throws InstantiationException, IllegalAccessException{
		insField(this,this.getClass().getDeclaredFields());
	}
	
	private void insField(Object current,Field[] fields) throws InstantiationException, IllegalAccessException{
		for(Field field : fields){
			field.setAccessible(true);
			if(field.getType().isInterface()){
				//如果是List接口,那么就实例一个ArrayList
				if("List".equals(field.getType().getSimpleName())){
					field.set(current, new ArrayList());
				}
				else if("Map".equals(field.getType().getSimpleName())){
					field.set(current, new HashMap());
				}
			}
			else
			{
				Object newInstance = field.getType().newInstance();
				field.set(current, newInstance);
				
				//只有com.limaoyuan包的类才会去迭代实例子类中的域实例
				if(field.getType().getPackage().getName().contains("com.limaoyuan")){
					Field[] subFields = newInstance.getClass().getDeclaredFields();
					insField(newInstance, subFields);
				}
			}
		}
	}
}

 

Reflection.java

 

package com.limaoyuan.reflection;

public class Reflection {

	/**
	 * @param args
	 * @throws IllegalAccessException 
	 * @throws InstantiationException 
	 */
	public static void main(String[] args) throws InstantiationException, IllegalAccessException {
		Main main = new Main();
		main.ins();
		System.out.println(main.getA()+"  " + main.getB() + "  " + main.getA().getB()+ "  " + main.getA().getC());
		System.out.println("list.size=" + main.getaList().size()+" , map.size=" + main.getMap().size());
		System.out.println("hashmap.size=" + main.getHashmap().size());
	}

}
 

 

你可能感兴趣的:(java反射)