JAVA应用运行时加载jar包

时间:2023-02-11 09:16:18

在c/s结构的应用中,很多时候我们都需要在启动时指定很多jar文件的路径,jar包少点还好,多了就很麻烦,还要维护他。

为方便起见,程序启动时,由main函数动态去加载指定路径下的jar文件到jvm,这样启动命令就干净了很多。

加载jar包的代码:

private static class JarLoader {
private URLClassLoader urlClassLoader;
public JarLoader(URLClassLoader urlClassLoader) {
this.urlClassLoader = urlClassLoader;
}

public void loadJar(URL url) throws Exception {
Method addURL = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
addURL.setAccessible(true);
addURL.invoke(urlClassLoader, url);
}
}

private static void loadjar(JarLoader jarLoader, String path) throws MalformedURLException, Exception{
File libdir = new File(path);
if (libdir != null && libdir.isDirectory()) {

File[] listFiles = libdir.listFiles(new FileFilter() {

@Override
public boolean accept(File file) {
// TODO Auto-generated method stub
return file.exists() && file.isFile() && file.getName().endsWith(".jar");
}
});

for (File file : listFiles) {
jarLoader.loadJar(file.toURI().toURL());
}

}else{
System.out.println("[Console Message] Directory ["+path+"] does not exsit, please check it");
System.exit(0);
}
}

public static void main(String[] args) {
JarLoader jarLoader = new JarLoader((URLClassLoader)ClassLoader.getSystemClassLoader());

loadjar(jarLoader, System.getProperty("user.dir")+"/lib");

}


这样,我们在启动的时候就java -jar app.jar 就好了,其他Jar包由main函数搞定。