I am developing a multi-module Java application. Each module contains several resource bundles: when a class Demo.java requires translations, a resource bundle Demo.properties in the same package is created. As the application is not supposed to crash when a translation is missing, I want the translation key to be used as a fallback.
Since Java 9, a ResourceBundleProvider should be the right way to implement custom resource bundles:
package my.app.core;
public class KeyFallbackResourceBundleProvider extends AbstractResourceBundleProvider {
@Override
public ResourceBundle getBundle(String baseName, Locale locale) {
var bundle = super.getBundle(baseName, locale);
return new ResourceBundle() {
@Override
protected Object handleGetObject(String key) {
try {
return bundle.getObject(key);
} catch (MissingResourceException e) {
return key;
}
}
@Override
public Enumeration<String> getKeys() {
return bundle.getKeys();
}
};
}
}
Now, I need ResourceBundle#getBundle(String) to use that provider in every class that loads a resource bundle. It seems, however, that the name the provider is supposed to have depends on the name of the bundle to load, which is not acceptable for my use case. In addition, I want to use the same provider for all modules (which can directly depend on it).
Is there a way of achieving this without having to implement a ResourceBundleProvider for every resource bundle? And if not, is there any other way to implement the key fallback mechanism I described?