views:

65

answers:

2

Hi. I started to work in translating a Java program which has tens of dialog classes to deal with. I wonder how is it possible to create a parameter that is understood in all of those classes, without having to declare it in each one.

Actualy are two parameters. Tried with something like:

public Locale currentLocale = new Locale("en");
public ResourceBundle text = ResourceBundle.getBundle("MessagesBundle", currentLocale);

in the launching class of the program but had no luck.

Any tip?

A: 

Set a Parent ResourceBundle

Use the ResourceBundle.setParent() method. If a specific key cannot be found in the current ResourceBundle it will search the parent ResourceBundle.

getBundle will automatically search for parents

As the JavaDoc for ResourceBundle.getBundle(String, Locale, ClassLoader) states, this automatically happens when you load a resource bundle for a specific Locale and a bundle with the same base name can be found without the locale suffix.

In your example the ResourceBundle will be loaded from a file (.properties extension is optional) named:

MessagesBundle_en.properties

But it will also look for a generic

MessagesBundle.properties

and set this as the parent. If you provide this generic file as well, it will be used as a default whenever a key in a specific locale bundle cannot be found.

krock
.properties is needed, at least when testing under Linux.
Gabriel A. Zorrilla
+1  A: 

without having to declare it in each one.

There are two general approaches:

  1. Singleton pattern.
  2. Store the reference in the thread using ThreadLocal.

Either way, you need to take a lot of caveats into account. Singletons doesn't work well in environments with multiple classloaders/JVM's and ThreadLocals doesn't work well when you spawn multiple threads yourself to process the business task. You need to understand those caveats very well before continuing.

The safe approach would be to create the object only once during application's startup in some front controller class and pass it as argument into the business/model objects whenever needed.

BalusC