java动态加载插件化编程详解

作者: adm 分类: java 发布时间: 2021-11-05

对于java程序员来说,插件化是一件很酷的功能,小二有幸在工作中实现了此功能。

需要将mysql的数据通过canal同步至kafka/mysql/hdfs等

实现

public class PluginManager {
private final static Logger logger = LoggerFactory.getLogger(SendMessageFactory.class);

private URLClassLoader urlClassLoader;

public PluginManager(List<Plugin> plugins) throws MalformedURLException {
init(plugins);
}
//将所有插件动态加载至JVM中
private void init(List<Plugin> 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;
}
}
/**
* 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<Plugin> plugins) throws MalformedURLException {
init(plugins);
}
//将所有插件动态加载至JVM中
private void init(List<Plugin> 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;
}
}

然后就可以进行插件的调用了。

如果觉得我的文章对您有用,请随意赞赏。您的支持将鼓励我继续创作!