November 22, 2002

What is the difference between Class.getResource() and ClassLoader.getResource() ?

Because Class.getResource() eventually delegates to ClassLoader.getResource(), the two methods are indeed very similar. However, the first method is often preferable. It provides a nice extra feature: it looks up package-local resources. As an example, this code snippet


executed from a class some.pkg.MyClass looks for a resource deployed as some/pkg/ You might wonder why this is better then the equivalent


The reason is the possibility for future refactoring. Should you decide to rename pkg to betterpkgname and move all classes and resources into the new package, the first code snippet requires no further code changes. The second code snippet embeds the old package name in a string literal—something that is easy to forget and can become a runtime error later.

Another advantage of Class.getResource() is that it does not require the getClassLoader runtime security permission, which the other approach requires.

I should mention a few extra details. Is it better to acquire the relevant Class object using the getClass() instance method or using MyClass.class? The answer depends on whether you plan to have classes in other packages extend MyClass. Since getClass() always returns the most derived class, it might return a class in a package different from some.pkg, possibly coded after MyClass is conceived. If this is a possibility, you should safeguard against potential lookup errors by using the class literal syntax form, MyClass.class. As an added benefit, it also works from static methods.

Vladimir Roubtsov has programmed in a variety of languages for more than 12 years, including Java since 1995. Currently, he develops enterprise software as a senior developer for Trilogy in Austin, Texas.

Learn more about this topic