Twostrategies for loading resource bundles and property files from Java code
By VladimirRoubtsov, JavaWorld.com, 11/22/02
From:http://www.javaworld.com/javaworld/javaqa/2002-11/02-qa-1122-resources.html
Q: Whatis 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 oftenpreferable. It provides a nice extra feature: it looks up package-localresources. As an example, this code snippet
getClass().getResource("settings.properties");
executed from a class some.pkg.MyClass
looksfor a resource deployed as some/pkg/settings.properties
. You mightwonder 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
andmove all classes and resources into the new package, the first code snippetrequires no further code changes. The second code snippet embeds the oldpackage name in a string literal—something that is easy to forget and canbecome a runtime error later.
Another advantage of Class.getResource()
isthat it does not require the getClassLoader
runtime securitypermission, which the other approach requires.
I should mention a few extra details. Is it better toacquire the relevant Class
object using the getClass()
instance method or using MyClass.class
? The answer depends onwhether you plan to have classes in other packages extend MyClass
.Since getClass()
always returns the most derived class, it might return aclass in a package different from some.pkg
, possibly coded after MyClass
is conceived. If this is a possibility, you should safeguard against potentiallookup errors by using the class literal syntax form, MyClass.class
.As an added benefit, it also works from static methods.
About the author
Vladimir Roubtsov has programmed in avariety of languages for more than 12 years, including Java since 1995.Currently, he develops enterprise software as a senior developer for Trilogy inAustin, Texas.