假设下面的jar文件遵循分层结构。
application.jar
demo
Main.class
lib
dep.jar
dep
DependencyMain.class
我想用lib / dep.jar创建类加载器并加载DependencyMain类。
private static void loadTest() throws Exception {
File jarFile = new File(Main.class.getProtectionDomain().getCodeSource().getLocation().getPath());
final JarFile jar = new JarFile(jarFile);
final Enumeration<JarEntry> entries = jar.entries();
String file = "jar:" + jarFile.toURI() + "!/";
while (entries.hasMoreElements()) {
JarEntry entry = entries.nextElement();
if(entry.getName().endsWith("dep.jar") {
// HAVE TO CHANGE
URL jarUrl = new URL(file + name);
final JarURLConnection connection = (JarURLConnection)jarUrl.openConnection();
final URL url = connection.getJarFileURL();
ClassLoader classLoader = new URLClassLoader(new URL[]{jarUrl}, Main.class.getClassLoader());
Class<?> clazz = classLoader.loadClass("dep.DependencyMain");
// i want to load dep.DependencyMain class at here
break;
}
}
}