... until the collector arrives ...

This "blog" is really just a scratchpad of mine. There is not much of general interest here. Most of the content is scribbled down "live" as I discover things I want to remember. I rarely go back to correct mistakes in older entries. You have been warned :)

2010-06-08

Leading Slash vs. ClassLoader.getResource()

When using the Java API ClassLoader.getResource(), be sure that your resource path does not start with a slash. If you do, then the result will be null. This behaviour is different from Class.getResource(), where a leading slash has special meaning.

At least, this is how Sun's implementation behaves. The Javadoc for ClassLoader.getResource() is not too clear on this point (although the implication is there). I found this out by reading the source.

I found this problem while troubleshooting a pesky unit test that would work within Eclipse when run as a JUnit Plug-in Test, but would fail when run as a basic JUnit Test. It turns out that the Eclipse implementation of ClassLoader.getResource() is tolerant of the leading slash. Almost everywhere in the code base, the resource names were correct and did not have a leading slash. In the particular case in point, however, a leading slash had been inadvertently added -- a difficult mistake to spot.

Blog Archive