我在类路径中有三个资源文件:
labels.properties:
language = Default
labels_en.properties:
language = English
labels_fr.properties:
language = French
有没有办法获得一个始终加载labels.properties的ResourceBundle对象无关紧要我的默认语言环境是什么?
ResourceBundle.getBundle(“labels”)返回与当前默认语言环境对应的一个(如预期的那样).
我能找到的唯一方法是将默认语言环境设置为不存在的语言环境,但这可能会破坏其他模块.
谢谢!
Locale.setDefault( Locale.ENGLISH); Assert.assertEquals( "English",ResourceBundle.getBundle( "labels").getString( "language")); Locale.setDefault( Locale.FRENCH); Assert.assertEquals( "French",ResourceBundle.getBundle( "labels").getString( "language")); Assert.assertEquals( "French",ResourceBundle.getBundle( "labels",new Locale( "do-not-exist")).getString( "language")); Locale.setDefault( new Locale( "do-not-exist")); Assert.assertEquals( "Default",ResourceBundle.getBundle( "labels").getString( "language"));
解决方法
您可以传入
ResourceBundle.Control,无论请求的Locale如何,始终只搜索根ResourceBundle:
ResourceBundle rootOnly = ResourceBundle.getBundle("labels",new ResourceBundle.Control() { @Override public List<Locale> getCandidateLocales(String name,Locale locale) { return Collections.singletonList(Locale.ROOT); } });