title: What is the difference between Class.getResource() and ClassLoader.getResource()?
body: <p>I wonder what the difference is between <code>Class.getResource()</code> and <code>ClassLoader.getResource()</code>?</p>
  
  <p><em>edit: I especially want to know if any caching is involved on file/directory level. As in "are directory listings cached in the Class version?"</em></p>
  
  <p>AFAIK the following should essentially do the same, but they are not:</p>
  
  <pre><code>getClass().getResource() 
  getClass().getClassLoader().getResource()
  </code></pre>
  
  <p>I discovered this when fiddling with some report generation code that creates a new file in <code>WEB-INF/classes/</code> from an existing file in that directory. When using the method from Class, I could find files that were there at deployment using <code>getClass().getResource()</code>, but when trying to fetch the newly created file, I recieved a null object. Browsing the directory clearly shows that the new file is there. The filenames were prepended with a forward slash as in "/myFile.txt".</p>
  
  <p>The <code>ClassLoader</code> version of <code>getResource()</code> on the other hand did find the generated file. From this experience it seems that there is some kind of caching of the directory listing going on. Am I right, and if so, where is this documented?</p>
  
  <p>From the <a href="http://download.oracle.com/javase/1,5.0/docs/api/java/lang/Class.html#getResource%28java.lang.String%29">API docs</a> on <code>Class.getResource()</code></p>
  
  <blockquote>
    <p>Finds a resource
    with a given name. The rules for
    searching resources associated with a
    given class are implemented by the
    defining class loader of the class.
    This method delegates to this object's
    class loader. If this object was
    loaded by the bootstrap class loader,
    the method delegates to
    ClassLoader.getSystemResource(java.lang.String).</p>
  </blockquote>
  
  <p>To me, this reads "Class.getResource is really calling its own classloader's getResource()". Which would be the same as doing <code>getClass().getClassLoader().getResource()</code>. But it is obviously not. Could someone please provide me with some illumination into this matter?</p>