Document directory
- Twostrategies for loading resource bundles and property files from Java code
- About the author
Twostrategies for loading resource bundles and property files from Java code
By region mirroubtsov, 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:BecauseClass.getResource()
Eventually delegates
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 classsome.pkg.MyClass
Looksfor a resource deployed
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. shocould you decide to rename
pkg
Tobetterpkgname
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 advantageClass.getResource()
Isthat it does not require
getClassLoader
Runtime securitypermission, which the other approach requires.
I shocould mention a few extra details. Is it better toacquire the relevant
Class
Object usinggetClass()
Instance method or using
MyClass.class
? The answer depends onwhether you plan to have classes in other packages extend
MyClass
. SincegetClass()
Always ReturnsMost derivedClass, it might return Aclass in a package different from
some.pkg
, Possibly coded afterMyClass
Is conceived. If this is a possibility, you shoshould 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 versions for more than 12 years, including Java since 1995. Currently, he develops enterprise software as a senior developer for trilogy inaustin, Texas.