千言万语不如一则用例。
关键点:
ClassLoader
加载配置文件。Properties
对象存储配置文件。Class.forName
方法加载类。- 通过
Class
对象的getMethod
获取方法。 - 通过
Class
对象的newInstance
方法创建实例。 - 通过
Method
对象的invoke
执行。
package com.zfy.study.reflect;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.util.Properties;
public class ReflectDemo5 {
public static void main(String[] args) throws Exception {
// 读取配置文件需要用到 ClassLoader
ClassLoader classLoader = ReflectDemo5.class.getClassLoader();
// 读取配置文件
InputStream resourceAsStream = classLoader.getResourceAsStream("pro.properties");
// 使用 Properties 对象存储配置文件内容
Properties properties = new Properties();
properties.load(resourceAsStream);
// 获取配置中的类名
String className = properties.getProperty("className");
// 获取配置中的方法名
String methodName = properties.getProperty("methodName");
// 加载类对象
Class<?> cls = Class.forName(className);
// 获取类方法
Method method = cls.getMethod(methodName);
// 创建类的实例
Object o = cls.newInstance();
// 通过反射执行方法
method.invoke(o);
}
}
pro.properties
className=com.zfy.study.reflect.Person
methodName=eat
Person
类
package com.zfy.study.reflect;
public class Person {
public Person() {
}
public void eat(){
System.out.println("eat ...");
}
}
执行结果:
eat ...