java UrlClassLoader:findResources 返回 null,但 loadClass 返回类
我将其作为 UrlClassLoader 的默认子级,添加了所有 jar 文件,然后
public void addFile(String path) throws MalformedURLException {
String urlPath = "jar:file:/" + path + "!/";
System.out.println("------------------");
System.out.println("urlPath = " + urlPath);
URL url = new URL(urlPath);
System.out.println("url = " + url);
super.addURL(url);
System.out.println("g = " + getURLs().length);
System.out.println("==================");
}
我尝试从加载器获取一些类:
System.out.println("cl.loadClass() = " + cl.loadClass("com.company.project.SomeClass"));
它正常返回类。
当我尝试按包查找所有类时:
resources = cl.findResources("com/company/");
它返回空枚举。 为什么?
I made as default child of UrlClassLoader, added all my jar files by
public void addFile(String path) throws MalformedURLException {
String urlPath = "jar:file:/" + path + "!/";
System.out.println("------------------");
System.out.println("urlPath = " + urlPath);
URL url = new URL(urlPath);
System.out.println("url = " + url);
super.addURL(url);
System.out.println("g = " + getURLs().length);
System.out.println("==================");
}
then i'm trying to get some class from loader:
System.out.println("cl.loadClass() = " + cl.loadClass("com.company.project.SomeClass"));
It returns class normally.
When i'm try to find all classes by package:
resources = cl.findResources("com/company/");
It returns empty enumeration.
Why?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
ClassLoader
的 Java API 没有提供枚举包中所有元素的标准方法。由于您使用自己的 ClassLoader,因此您可以在其中实现一个函数,该函数在 JAR 内执行自定义搜索。一些链接。
类似问题:
如何从类路径中的 Java 包中读取所有类?
如何读取 Jar:如何列出 JAR 文件中的文件?
The Java API of
ClassLoader
does not provide a standard way to enumerate all the elements in a package. Since you use your ownClassLoader
, you can implement a function in it which performs a custom search inside the JARs.A few links.
Similar question:
How do I read all classes from a Java package in the classpath?
How to read a Jar: How do I list the files inside a JAR file?
我不认为
findResources()
做你认为它应该做的事情。根据 其API文档:这听起来根本不像会做前缀匹配(如果你仔细想想,给定一个 HTTP URL,这是不可能做到的)。它可能做的事情是在构造
URLClassLoader
时使用的所有基本 URL 中查找给定的全名,因此,如果您调用findResources("log4j. properties")
并且类加载器已使用 5 个 JAR 构建,其中 3 个在根目录包含文件log4j.properties
,则该方法将返回所有 3 个。I don't think
findResources()
does what you think it shuld do. According to its API doc:That doesn't sound like it would do a prefix match at all (and if you think about it, it would be impossible to do that, given a HTTP URL). What it probably does is look for the given full name in all of the base URLs the
URLClassLoader
has been constructed with, so if you callfindResources("log4j.properties")
and the classloader has been constructed with 5 JARs, 3 of which contain a filelog4j.properties
at the root, then the method will return all 3.