javaurlclassloader

URLClassLoader - Difference between getResource and findResource


The URLClassLoader has two functions for getting a resource as an URL. One is named getResource and is inherited, and one is from the URLClassLoader and it is named findResource. Both returns an URL. They look very similar, what is the difference between them?

getResource method comment: Finds the resource with the given name. A resource is some data (images, audio, text, etc) that can be accessed by class code in a way that is independent of the location of the code. [continues]

findResource method comment: Finds the resource with the specified name on the URL search path.


Solution

  • The getResource method uses the standard classloader hierarchy approach: ClassLoaders have parents. The getResource method will ask the parent to load it, and only if the parent cannot find the requested resource, will it try to load it itself.

    findResource on the other hand is ONLY this classloader's attempt to find a resource; it does not query parent at all.

    Generally, you should use getResource (and it will use findResource if need be).