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

前言

对于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<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;

}

}

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

以上是 java动态加载插件化编程详解 的全部内容, 来源链接: utcz.com/z/323701.html

回到顶部