November 22, 2002
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.
Learn more about this topic
- See the Java Q&A index page for the full Q&A catalog
http://www.javaworld.com/columns/jw-qna-index.shtml - For more than 100 insightful Java tips, visit JavaWorld's Java Tips index page
http://www.javaworld.com/columns/jw-tips-index.shtml - Browse the Core Java section of JavaWorld's Topical Index
http://www.javaworld.com/channel_content/jw-core-index.shtml - Get more of your questions answered in our Java Beginner discussion
http://forums.devworld.com/webx?50@@.ee6b804 - Sign up for JavaWorld's free weekly email newsletters
http://www.javaworld.com/subscribe - You'll find a wealth of IT-related articles from our sister publications at IDG.net