一、配置文件
文件位置:src文件下
文件名:ConfigurationFile
文件内容:
className=com.config.Class_Test
二、Class_Test类
类名:Class_Test
位置:src的com.config包里
代码:
package com.config;
public class Class_Test {
public Class_Test() {
System.out.println("无参构造");
}
public Class_Test(String name) {
System.out.println("有参构造:" + name);
}
}
三、测试类Test
类名:Test
位置:src的com.config包里
代码:
package com.config;
import java.io.FileReader;
import java.lang.reflect.Constructor;
import java.util.Properties;
public class Test {
private static String radConfigurationFile() throws Exception {
Properties p = new Properties();
String ConfigurationFile = System.getProperty("user.dir") + "\\src\\" + "ConfigurationFile";//System.getProperty("user.dir")获取项目位置
FileReader fr = new FileReader(ConfigurationFile);
p.load(fr);
fr.close();
// 获取属性
String str = p.getProperty("className");
return str;
}
private static void getStructure(String className) throws Exception {
Class<?> c = Class.forName(className);//反射
// 获取构造
Constructor<?> constr = c.getConstructor();
// 实例化对象
Object o = constr.newInstance();
// 获取带参构造方法
constr = c.getConstructor(String.class);
// 实例化对象
o = constr.newInstance("江");
}
public static void main(String[] args) throws Exception {
String className = radConfigurationFile();
getStructure(className);
}
}
运行结果:
无参构造
有参构造:江