开发者

java UrlClassLoader: findResources returns null, but loadClass returns classes

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.o开发者_如何学Gout.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?


The Java API of ClassLoader does not provide a standard way to enumerate all the elements in a package. Since you use your own ClassLoader, 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?


I don't think findResources() does what you think it shuld do. According to its API doc:

Returns an Enumeration of URLs representing all of the resources on the URL search path having the specified name.

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 call findResources("log4j.properties") and the classloader has been constructed with 5 JARs, 3 of which contain a file log4j.properties at the root, then the method will return all 3.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜