Got resources?

Two strategies for loading resource bundles and property files from Java code

November 22, 2002

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

A
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

     getClass().getResource("settings.properties");

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

getClass().getClassLoader().getResource("some/pkg/settings.properties");

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

Recommended
Join the discussion
Be the first to comment on this article. Our Commenting Policies
See more