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

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

I wrote a class loader that gets a callback for getResources (), and the resource is the name of the folder. In classloader, I have the root path from which the resource is being requested.

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

I don't understand how to create Enumeration , how to implement its hasMoreElements() and nextElement() inside getResources() . I do not see the connection between them.

Can't I find the subdirectory from the root and return the absolute path of the resource as the URL? why do you need to create this complex Enumeration ?

Thanks, Vimal

+4
source share
2 answers

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

In any case, you can easily add a logger inside, delegate the method to the parent class loader and see what is requested and returned by the parent class loader.

UPDATE

If, according to your comment, you want to load classes / resources from a path that is created at runtime, you should do the following: when the path is passed to the classloader (say /home/user1/ ), it must recursively list its contents storing the files in two different collections - class files and other files. The first collection will be used to load classes, the second for resources.

For each file in the resource collection, you determine its resource path in accordance with http://docs.oracle.com/javase/6/docs/api/java/lang/ClassLoader.html#getResource%28java.lang.String%29 and get the URL from the file: URL url = file.toURI().toURL(); This path and the URL that you store as a key-> value somewhere on the map, and use it in the method in question.

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

+2
source

Enumeration is a very old Java class that has been replaced by the new Collections library. You can get it by creating a Collection (of one item) and then typing Collections.enumeration() on it:

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

Source: https://habr.com/ru/post/1403961/


All Articles