You can trick the ResourceBundle
class to cache a bundle instance using a different ClassLoader
than used for the actual lookup in the key.
ResourceBundle rb=ResourceBundle.getBundle("Resources", new ResourceBundle.Control() {
@Override
public long getTimeToLive(String baseName, Locale locale) {
return Long.MAX_VALUE;
}
@Override
public ResourceBundle newBundle(String baseName, Locale locale,
String format, ClassLoader loader, boolean reload)
throws IllegalAccessException, InstantiationException, IOException {
return super.newBundle(baseName, locale, format, defaultLoader, reload);
}
});
Note that the getBundle
invocation is using the default SystemClassLoader (or caller ClassLoader
) as no class loader is specified. This is the ClassLoader
used in the key for caching the result. But the custom Control
implementation replaces the ClassLoader
with your defaultLoader
instance when looking up the real bundle.
Note that you should perform this action right before the lookup action of the 3rd party library. This control says that the bundle should never expire but it might still get freed when the JVM is low on memory.
Note that ResourceBundle
also caches failures so this trick must be applied before someone else tries to lookup that bundle.