Is there a good alternative to gettext _() method in Java?
It is a common way to decouple text messages and source code in C/Python/PHP/etc by means of gettext set of utilities. I'm trying to do something similar in my Java project, according to this instruction. Is it the best possible way? Or I should try something different and more advanced?
ps. I would like to avoid complex initialization and ideally my Java code should look like:
[...]
public String howBi开发者_JAVA技巧gIsTheFile(File f) {
String name = f.getAbsolutePath();
long length = f.length();
return _("The file %s is %d bytes long", name, length);
}
Something like gettext-commons maybe?
I assume this question is about stand-alone application (command-line, SWING, etc) and not about server-side application (with multiple users accessing concurrently).
In stand-alone application, the easiest is to create a single static accessor class that would be responsible for loading a single resource bundle and then looking up strings in that resource bundle.
Something like this:
public class ResourceUtil {
private static ResourceBundle rb;
static {
//set the default locale
setLocale(Locale.ENGLISH);
}
public static void setLocale(Locale locale) {
rb = ResourceBundle.getBundle("Resources", locale);
}
public static String tr(String key, Object... args) {
return MessageFormat.format(rb.getString(key), args);
}
}
You can change the active locale with setLocale(Locale)
method and access translated strings with tr(String,Object...)
method.
Then, you could call it from your class like this:
import static ResourceUtil.tr;
public String howBigIsTheFile(File f) {
String name = f.getAbsolutePath();
long length = f.length();
return tr("The file %s is %d bytes long", name, length);
}
Notice the static import.
Disclaimer: all provided code is on pseudo-code level and is not guaranteed to compile.
Depending on the size of your application, you might find it useful to use IDE string externalization support (e.g. see chapter in Eclipse JDT help, I'm sure other IDEs have some similar features).
You could also use several resource bundles and/or several static classes - it depends on the size of your application and your personal preference. See this question for further debate about this.
In a server-environment using static approach like above would lead into issues as different users would have different locales. Depending on your webapp framework, you would solve this issue differently (e.g. use MessageSource in Spring).
If you think about I18N/L10N, Java has its own mechanism here: the properties file. You can see an example in the internationalization tutorials. It's even simpler than gettext stuff :).
精彩评论