Java反射——根据配置文件,实例化对象

案例:根据配置文件,实例化对象

src下创建一个“配置文件”config.txt,内容如下:

className=ahjava.p07reflect.Cat
package ahjava.p07reflect;
import java.io.FileReader;
import java.lang.reflect.Constructor;
import java.util.Properties;
class Cat {
	public Cat() {
		System.out.println("Cat构造");
	}
	public Cat(String name) {
		System.out.println("Cat构造:" + name);
	}
}
public class T34读取配置造对象 {
	public static void main(String[] args) throws Exception {
		String className = 读取配置文件();
		get构造方法(className);
	}
	private static String 读取配置文件() throws Exception {
		// 读,载,关
		Properties p = new Properties();
		String _configPath = System.getProperty("user.dir") + "\src\ahjava\" + "config.txt";
		FileReader fr = new FileReader(_configPath);
		p.load(fr);
		fr.close();
		// 获取属性
		String str = p.getProperty("className");
		return str;
	}
	private static void get构造方法(String className) throws Exception {
		Class<?> c = Class.forName(className);
		// 获取构造
		Constructor<?> constr = c.getConstructor();
		// 实例化对象
		Object o = constr.newInstance();
		System.out.println(o);
		// 获取带参构造方法,并实例化对象
		constr = c.getConstructor(String.class);
		o = constr.newInstance("Tiger");
		System.out.println(o);
	}
}
Cat构造
ahjava.p07reflect.Cat@15db9742
Cat构造:Tiger
ahjava.p07reflect.Cat@6d06d69c
原文地址:https://www.cnblogs.com/tigerlion/p/11182846.html