This week's book giveaway is in the Design forum.
We're giving away four copies of Design for the Mind and have Victor S. Yocco on-line!
See this thread for details.
Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to check if a given key exists in a resource bundle?

 
smee bond
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I want to use the following code:

ResourceBundle rb = ResourceBundle.getBundle ("sample");
String from = rb.getString("from.address");

Before getting the "value", that I want make sure the key "from.address" exists in the resource bundle. Is there a way to check if the key exists and then proceed further?
 
Joanne Neal
Rancher
Posts: 3742
16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Do you mean something like a ResourceBundle.containsKey() method ?

Edit
Whoops - just noticed my sarcasm may have been a little misplaced. That method is only available in java 1.6. If you're not using 1.6, I guess you could write your own method that does a get and returns false or null if a MissingResourceException exception is thrown.

[ December 13, 2007: Message edited by: Joanne Neal ]
[ December 13, 2007: Message edited by: Joanne Neal ]
 
smee bond
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am using 1.5, so I cannot use ResourceBundle.containsKey() I guess. Thanks for the suggestion regarding the method use.....I wanted to do something like that but is it a good practice to ask the system to throw the exception and capture it to satisfy my condition?
 
Joanne Neal
Rancher
Posts: 3742
16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I can't think of any other way off the top of my head. You could download the 1.6 jdk and have a look at the source code to see how the containsKey method is implemented.
 
Rob Spoor
Sheriff
Pie
Posts: 20511
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Since all the good methods (containsKey(), keySet()) haven't been added until Java 6, there are two ways to go:

1) catch the MissingResourceException
2) use the Enumeration returned by getKeys() and check all of them.

Of course neither one is a great option.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic