Java 静态资源包
我目前正在为使用ResourceBundle的应用程序制作资源。问题是,使用当前的代码来调度资源,我需要在每次需要时创建一个资源包实例,我猜这不是一个好主意,因为我会一次又一次地加载资源 第二种解决方案是将bundle划分为多个,但最终的bundle只有2-3个字符串,大约15个bundle 我的问题是: 有没有一种方法可以简单地将所有资源加载到一个静态类中并从那里访问它们 我制作了这段代码,它似乎适合我,但我怀疑它的质量Java 静态资源包,java,static,resources,resourcebundle,Java,Static,Resources,Resourcebundle,我目前正在为使用ResourceBundle的应用程序制作资源。问题是,使用当前的代码来调度资源,我需要在每次需要时创建一个资源包实例,我猜这不是一个好主意,因为我会一次又一次地加载资源 第二种解决方案是将bundle划分为多个,但最终的bundle只有2-3个字符串,大约15个bundle 我的问题是: 有没有一种方法可以简单地将所有资源加载到一个静态类中并从那里访问它们 我制作了这段代码,它似乎适合我,但我怀疑它的质量 public class StaticBundle { priv
public class StaticBundle
{
private final static ResourceBundle resBundle =
ResourceBundle.getBundle("com.resources");
public final static String STRING_A = resBundle.getString("KEY_A");
public final static String STRING_B = resBundle.getString("KEY_B");
public final static String STRING_C = resBundle.getString("KEY_C");
}
有了它,我可以调用StaticBundle.STRING\u A
并在项目中的任何位置获取值,但是由于bundle与类本身同时初始化。。。程序很可能没有时间从首选项加载适当的本地文件
有没有一个很好的方法来做这件事或任何其他可能的解决方案
谢谢您可以创建一个singleton类:
public class MyResouceBundle extends ResourceBundle {
private static MyResourceBundle instance = new MyResouceBundle();
// private constructor, no one can instantiate this class, only itself
private MyResourceBundle() {
}
public ResourceBundle getInstance() {
return instance;
}
}
然后,每个人都将使用访问该类的同一实例(例如,获取KEY_A的字符串):
如果您只想使用默认语言环境的消息,那么您所拥有的就可以了 或者,您可以让调用者指定它需要的键,而不是使用常量,如下所示:
public static String getMessage(String key) {
return resBundle.getString(key);
}
如果您希望支持多个区域设置,那么通常的方法是使用
映射
映射如果您只使用默认区域设置加载密钥,那么您拥有的一切都很好。但不要太担心性能:ResourceBundle.getBundle()
使用缓存,并且不会在每次调用时重新加载资源。事实上,我在一开始就更改了运行时的默认本地值,因此我不需要在每次需要资源时都获取本地值(我有点懒)。所以你的第二个解决方案对我不合适,我喜欢这个想法。最后,我将常量设置为集中在需要更改资源键的位置(同样是我的懒惰)。将捆绑包存储在地图中没有意义ResourceBundle.getBundle()
已经以线程安全的方式做到了这一点,并且做得很好。@JBNizet您当然是对的。我们在一个项目中有一个定制解决方案,我们使用Map
来定制解决方案。我的记忆背叛了我,认为我们有一张地图。我已编辑了我的答案以更正此问题。谢谢你的评论
public static String getMessage(String key) {
return resBundle.getString(key);
}
public static String getMessage(String key, Locale locale) {
Map<String, String> bundle = bundles.get(locale); // this is the map with all bundles
if (bundle == null) {
// load the bundle for the locale specified
// here you would also need some logic to mark bundles that were not found so
// to avoid continously searching bundles that are not present
// you could even return the message for the default locale if desirable
}
return bundle.get(key);
}