【发布时间】:2017-08-02 07:29:21
【问题描述】:
这是我想要实现的目标。我们有一个在 IBM Domino 服务器上作为 servlet 运行的应用程序。 应用程序使用资源包根据浏览器语言获取翻译的消息和标签。
我们希望让客户能够覆盖某些值。 我们不能在运行时修改 .jar 中的 bundle_lang.properties 文件。 所以这个想法是提供额外的 bundleCustom_lang.properties 文件以及 .jar
这个包可以在运行时使用
加载private static void addToClassPath(String s) throws Exception {
File file = new File(s);
URLClassLoader cl = (URLClassLoader) ClassLoader.getSystemClassLoader();
java.lang.reflect.Method m = URLClassLoader.class.getDeclaredMethod("addURL", new Class[] { URL.class });
m.setAccessible(true);
m.invoke(cl, new Object[] { file.toURI().toURL() });
}
到目前为止,一切都很好,这在 Eclipse 中有效。在这里,我将 bundleCustom 文件放在工作区外部的目录中( /volumes/DATA/Temp/ )
一旦添加 ResourceBundle 可用,我们首先检查这个包的密钥。如果它返回一个值,则该值将用于翻译。如果没有返回值,或者文件不存在,则使用 .jar 中捆绑包中的值。
我的完整代码在这里
public class BundleTest2 {
static final String CUSTOM_BUNDLE_PATH = "/volumes/DATA/Temp/";
static final String CUSTOM_BUNDLE_MODIFIER = "Custom";
public static void main(String[] args) {
try {
addToClassPath(CUSTOM_BUNDLE_PATH);
System.out.println(_getTranslation("LabelBundle", "OutlineUsersAllVIP"));
} catch (Exception e) {
}
}
private static String _getTranslation(String bundle, String translation) {
return _getTranslation0(bundle, new Locale("de"), translation);
}
private static String _getTranslation0(String bundle, Locale locale, String key) {
String s = null;
try {
try {
ResourceBundle custom = ResourceBundle.getBundle(bundle + CUSTOM_BUNDLE_MODIFIER, locale);
if (custom.containsKey(key)) {
s = custom.getString(key);
}
} catch (MissingResourceException re) {
System.out.println("CANNOT FIND CUSTOM RESOURCE BUNDLE: " + bundle + CUSTOM_BUNDLE_MODIFIER);
}
if (null == s || "".equals(s)) {
s = ResourceBundle.getBundle(bundle, locale).getString(key);
}
} catch (Exception e) {
}
return s;
}
private static void addToClassPath(String s) throws Exception {
File file = new File(s);
URLClassLoader cl = (URLClassLoader) ClassLoader.getSystemClassLoader();
java.lang.reflect.Method m = URLClassLoader.class.getDeclaredMethod("addURL", new Class[] { URL.class });
m.setAccessible(true);
m.invoke(cl, new Object[] { file.toURI().toURL() });
}
}
当我从 servlet 内部尝试相同的操作时,我得到了 MissingResourceException。
我还尝试将 .properties 文件放入 custom.jar 中,并在调用 addToClassPath() 时提供完整路径(包括 .jar)。 显然,customization.jar 已加载(它被锁定在文件系统中),但我仍然得到 MissingResourceException。
我们已经在 addToClassPath 中使用了相同的代码来加载 Db2 驱动程序,并且按预期工作。
我错过了什么?
【问题讨论】:
标签: java runtime classpath resourcebundle