利用反射加载配置文件,并动态创建对象和调用方法实战
发布人:shili8
发布时间:2023-12-29 14:05
阅读次数:103
在Java开发中,我们经常会遇到需要动态加载配置文件,并根据配置文件中的信息动态创建对象和调用方法的情况。这种需求通常可以通过反射来实现,下面我们就来看一个实战案例。
假设我们有一个配置文件config.properties,内容如下:
class=com.example.MyClassmethod=doSomething
我们需要根据这个配置文件中的信息动态创建MyClass对象,并调用它的doSomething方法。
首先,我们需要编写一个工具类来加载配置文件并使用反射来创建对象和调用方法。下面是一个简单的示例代码:
javaimport java.io.InputStream;
import java.util.Properties;
public class ReflectUtil {
public static Object createObject(String className) throws Exception {
Class> clazz = Class.forName(className);
return clazz.newInstance();
}
public static void invokeMethod(Object obj, String methodName) throws Exception {
Class> clazz = obj.getClass();
clazz.getMethod(methodName).invoke(obj);
}
public static Properties loadConfig(String configFile) throws Exception {
Properties properties = new Properties();
InputStream inputStream = ReflectUtil.class.getClassLoader().getResourceAsStream(configFile);
properties.load(inputStream);
return properties;
}
}
接下来,我们可以编写一个测试类来使用这个工具类来实现动态加载配置文件,并创建对象和调用方法:
javapublic class Main {
public static void main(String[] args) {
try {
Properties properties = ReflectUtil.loadConfig("config.properties");
String className = properties.getProperty("class");
String methodName = properties.getProperty("method");
Object obj = ReflectUtil.createObject(className);
ReflectUtil.invokeMethod(obj, methodName);
} catch (Exception e) {
e.printStackTrace();
}
}
}
在这个示例中,我们首先使用ReflectUtil工具类加载了config.properties配置文件,然后根据配置文件中的信息动态创建了MyClass对象,并调用了它的doSomething方法。
通过这个实战案例,我们可以看到利用反射加载配置文件,并动态创建对象和调用方法是非常灵活和强大的,可以帮助我们实现各种动态配置和扩展的需求。当然,在实际开发中,我们需要注意反射的性能和安全性问题,避免滥用反射带来的潜在风险。

