Tomcat 通过在类加载器层次结构中重复调用来获取要扫描的 jar URL URLClassLoader.getURLS()
(自下而上)
系统类加载器出现问题,因为URLClassLoader.getURLS()
在执行 java 应用程序时不返回类路径 jarjava -jar <executable-jar>
请参阅:类加载器如何在清单类路径中加载类引用?
在上一篇文章中建议使用反射来访问系统类加载器实例中的私有字段,但这会带来几个问题:
于是我想出了另一种方法:
- 对于给定的类加载器,枚举所有可用的清单
cl.getResources("META-INF/MANIFEST.MF")
。这些清单可以是由当前类加载器或其上层类加载器管理的 jar。
- 对其父类加载器执行相同的操作
- 返回 (1) 中但不在 (2) 中的那些清单的 jar 集
此方法工作的唯一要求是类路径中的 jar 必须具有清单才能返回(要求不多)。
/**
* Returns the search path of URLs for loading classes and resources for the
* specified class loader, including those referenced in the
* {@code Class-path} header of the manifest of a executable jar, in the
* case of class loader being the system class loader.
* <p>
* Note: These last jars are not returned by
* {@link java.net.URLClassLoader#getURLs()}.
* </p>
* @param cl
* @return
*/
public static URL[] getURLs(URLClassLoader cl) {
if (cl.getParent() == null || !(cl.getParent()
instanceof URLClassLoader)) {
return cl.getURLs();
}
Set<URL> urlSet = new LinkedHashSet();
URL[] urLs = cl.getURLs();
URL[] urlsFromManifest = getJarUrlsFromManifests(cl);
URLClassLoader parentCl = (URLClassLoader) cl.getParent();
URL[] ancestorUrls = getJarUrlsFromManifests(parentCl);
for (int i = 0; i < urlsFromManifest.length; i++) {
urlSet.add(urlsFromManifest[i]);
}
for (int i = 0; i < ancestorUrls.length; i++) {
urlSet.remove(ancestorUrls[i]);
}
for (int i = 0; i < urLs.length; i++) {
urlSet.add(urLs[i]);
}
return urlSet.toArray(new URL[urlSet.size()]);
}
/**
* Returns the URLs of those jar managed by this classloader (or its
* ascendant classloaders) that have a manifest
* @param cl
* @return
*/
private static URL[] getJarUrlsFromManifests(ClassLoader cl) {
try {
Set<URL> urlSet = new LinkedHashSet();
Enumeration<URL> manifestUrls =
cl.getResources("META-INF/MANIFEST.MF");
while (manifestUrls.hasMoreElements()) {
try {
URL manifestUrl = manifestUrls.nextElement();
if(manifestUrl.getProtocol().equals("jar")) {
urlSet.add(new URL(manifestUrl.getFile().substring(0,
manifestUrl.getFile().lastIndexOf("!"))));
}
} catch (MalformedURLException ex) {
throw new AssertionError();
}
}
return urlSet.toArray(new URL[urlSet.size()]);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
Tomcat 注册问题:https ://bz.apache.org/bugzilla/show_bug.cgi?id=59226