java - Static ResourceBundle -
i making resources app using resourcebundle. thing is, current code dispatch resources need create instance of resource bundle every time need , can guess not idea, since end loading resources again , again.
the second solution divide bundle many, end bundles have 2-3 strings , 15 bundles.
my question is: there way simple load resources in single static class , access them there.
i made little piece of code seems work me doubt quality.
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"); }
with can call staticbundle.string_a
, value anywhere in project since bundle initialized @ same time class itself... highly possible program won't have time load proper local preferences.
is there way or other possible solution?
thank you
if intend have messages default locale have fine.
alternatively let caller specify key needs instead of having constants, this:
public static string getmessage(string key) { return resbundle.getstring(key); }
if support multiple locales usual approach have map<locale, resourcebundle>
map<locale, map<string, string>
load resources once each locale. in case class have method caller can specify locale:
public static string getmessage(string key, locale locale) { map<string, string> bundle = bundles.get(locale); // map bundles if (bundle == null) { // load bundle locale specified // here need logic mark bundles not found // avoid continously searching bundles not present // return message default locale if desirable } return bundle.get(key); }
edit: correctly pointed out @jb nizet (thanks) resourcebundle
stores map
. custom solution provided in source example, custom mechanism similar resourcebundle
used map
of map
s load translations of keys in property=value format, not files database. have incorrectly thought had map
of resourcebundle
in solution. source example fixed now.
Comments
Post a Comment