简体   繁体   中英

how to implement java.lang.Classloader getResources()?

I have searched quite a lot, but didnt find any satisfactory answer. so please forgive me if this is too obvious to you.

I have written a classloader which is getting a callback for getResources(), and the resource is a folder name. In the classloader i have the root path from which the resource is being asked for.

now the getResources() requires me to return an 'Enumeration' of URL.

I am not getting any idea how to create an Enumeration , how to implement its hasMoreElements() and nextElement() inside getResources() . I am not able to see the connection between the two.

Cant i simple search for the subpath from the root and return the absolute path of the resource as a URL? why need to create this complicated Enumeration ?

Thanks, VImal

Enumeration is a very old Java class that's been superceded by the newer Collections library. You can get one by creating a Collection (of a single element) and then calling Collections.enumeration() on it:

Enumeration<String> enumInstance = Collections.enumeration(Arrays.asList("Bla"));

Usually, the two most important methods, that you have to override in your own classloader, are public Class findClass(String name) and public InputStream getResourceAsStream(String name) . Others can be delegated to the parent classloader in most cases. That means that you must have a very special purpose in overriding getResources() . What is it?

In either case you can easily add put a logger inside, delegate method to parent classloader and see what is requested and returned by parent classloader.

UPDATE

If, as per your comment, you want to load classes/resources from a path which is generated at runtime , you should do the following: when path is passed to classloader (say /home/user1/ ), it should recursively list it's content storing files in two different collections - class files and other files. The first collection will be used for classloading, the second - for resources.

For each file in resource collection you define it's resource path according to http://docs.oracle.com/javase/6/docs/api/java/lang/ClassLoader.html#getResource%28java.lang.String%29 and get the URL from file: URL url = file.toURI().toURL(); These path and URL you store as key->value somewhere in a map and use it in method in question.

As for resource path, I believe it should be somewhat relative to the path, which was passed to your classloader: /home/user1/img/logo.gif => /img/logo.gif

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM