如何将内部类与ListResourceBundle结合使用?

时间:2018-09-19 04:14:31

标签: java

在BankTeller类中,我有3个内部类扩展了ListResourceBundle,即

  • BankTeller_ja_JP
  • BankTeller_el_GR
  • BankTeller_zh_CN

在BankTeller的主要方法中,我想使用这些类。我尝试使用

ResourceBundle res = ResourceBundle.getBundle("BankTeller$BankTeller",locale);
ResourceBundle res = ResourceBundle.getBundle("BankTeller.BankTeller",locale);

但是两个都给了我以下例外:

Exception in thread "main" java.util.MissingResourceException: Can't find bundle for base name BankTeller$BankTeller, locale el_GR
    at java.util.ResourceBundle.throwMissingResourceException(Unknown Source)
    at java.util.ResourceBundle.getBundleImpl(Unknown Source)
    at java.util.ResourceBundle.getBundle(Unknown Source)
    at lab10.BankTeller.displayValues(BankTeller.java:16)
    at lab10.BankTeller.main(BankTeller.java:12)

如何加载ResourceBundles?

1 个答案:

答案 0 :(得分:0)

如果您想使用嵌套类,那么您的BankTeller应该是 public static 嵌套类。 我已经在com.java.util包中创建了ResourceBundleTest类:

class ResourceBundleTest {

    @Test
    void getBundle_fromNestedStaticClass() {
        // given
        final Locale locale = new Locale("en", "GB");
        // when
        final ResourceBundle exampleBundle = ResourceBundle.getBundle("com.java.util.ResourceBundleTest$BankTeller", locale);
        // then
        assertEquals("Hello World!", exampleBundle.getString("greetings"));
    }

    public static class BankTeller_en_GB extends ListResourceBundle {

        @Override
        protected Object[][] getContents() {
            return new Object[][]{{"greetings", "Hello World!"}};
        }

    }
}