反射によるオブジェクトの作成(パラメータ付きおよびパラメータなしの構築方法)

3068 ワード

1、エンティティークラスを作成する
package adtec.reflect;

public class Person {

	String name;
	
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	// 
	public Person(String name) {
		super();
		this.name = name;
	}

	// 
	public Person(){
		
	}
	
	public void run(){
		System.out.println(getName() + " is running");
	}
	
	public void eat(){
		System.out.println(getName() + " is eating rice");
	}
}

 
2、定義によるクラスのインスタンス化
package adtec.reflect;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

import org.junit.Test;

public class ReflectPerson {

	/**
	 *  , 
	 */
	@Test
	public void noParamContruct(){
		String classStr = "adtec.reflect.Person";
		ClassLoader c1 = ClassLoader.getSystemClassLoader(); 
		Class clazz;
		try {
			clazz = c1.loadClass(classStr);
			Person person = (Person)clazz.newInstance();
			person.eat();
			person.run();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 *  , 
	 */
	@Test
	public void haveParamContruct(){
		String classStr = "adtec.reflect.Person";
		ClassLoader c1 = ClassLoader.getSystemClassLoader();
		try {
			Class clazz = c1.loadClass(classStr);
			Constructor construct = clazz.getConstructor(String.class);
			Person person = (Person)construct.newInstance("huangbiao");
			person.eat();
			person.run();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
		
	}
	
	/**
	 *  Class 
	 */
	@Test
	public void newObjectByClass(){
		String classStr = "adtec.reflect.Person";
		try {
			Person person = (Person)Class.forName(classStr).newInstance();
			person.eat();
			person.run();
		} catch (InstantiationException | IllegalAccessException
				| ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	
	
	
	
	
}