对于java程序员来说,插件化是一件很酷的功能,小二有幸在工作中实现了此功能。
背景:
需要将mysql的数据通过canal同步至kafka/mysql/hdfs等
实现
直接上代码
/**
* Created by shengjk1 on 2017/12/11
*/
public class PluginManager {
private final static Logger logger = LoggerFactory.getLogger(SendMessageFactory.class);
private URLClassLoader urlClassLoader;
public PluginManager(List plugins) throws MalformedURLException {
init(plugins);
}
//将所有插件动态加载至JVM中
private void init(List plugins) throws MalformedURLException {
int size = plugins.size();
URL[] urls = new URL[size];
for (int i = 0; i < size; i++) {
Plugin plugin = plugins.get(i);
String filePath = plugin.getJar();
urls[i] = new URL("file:" + filePath);
}
urlClassLoader = new URLClassLoader(urls);
}
public PluginService getInstance(String className) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
// 插件实例化对象,得到每一个插件具体的对象
Class> clazz = urlClassLoader.loadClass(className);
Object instance = clazz.newInstance();
return (PluginService) instance;
}
}
然后就可以进行插件的调用了。
有一点需要注意,那就是效率。反射真的降低效率吗?请移步
http://blog.csdn.net/jsjsjs1789/article/details/78719605