需求:根据配置文件中的内容创建相应的类的对象,并执行相应的方法
实现:
步骤:
注意:需要将配置文件放在src目录下,放在src目录下的任何文件,都会被编译到classes目录下,这样做的目的是为了让配置文件跟随编译后的class文件一起,因为交付用户使用的是class文件,而不是源代码。
如何读取src目录下的文件:使用类的加载器ClassLoader类的方法 :
InputStream getResourceAsStream(String name)
//文件1
package kehao.reflet;
public class Student {
public void sayHello(){
System.out.println("hello!I‘m a student!");
}
}
//文件2
package kehao.reflet;
public class Teacher {
public void sayHello(){
System.out.println("hello!I‘m a teacher!");
}
}
配置文件:reflect.properties
className = kehao.reflet.Teacher
methodName = sayHello
功能代码:
public class ReflectTest {
public static void main(String[] args) throws IOException, ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
ClassLoader classLoader = ReflectTest.class.getClassLoader();
InputStream is = classLoader.getResourceAsStream("reflect.properties");
Properties properties = new Properties();
properties.load(is);
String className = properties.getProperty("className");
String methodName = properties.getProperty("methodName");
Class aClass = Class.forName(className);
Object o = aClass.getConstructor().newInstance();
aClass.getMethod(methodName).invoke(o);
}
}
原文:https://www.cnblogs.com/kehao/p/14579623.html