繁体   English   中英

Java国际化 - 我是否必须为每个类加载资源包?

[英]Java internationalization - Do I have to load a resource bundle for every class?

诺布在这里。

我正在尝试实现基于命令行的程序的国际化。 以下是java国际化路径中提供的内容。

import java.util.*;

public class I18NSample {

    static public void main(String[] args) {

        String language;
        String country;

        if (args.length != 2) {
            language = new String("en");
            country = new String("US");
        } else {
            language = new String(args[0]);
            country = new String(args[1]);
        }

        Locale currentLocale;
        ResourceBundle messages;

        currentLocale = new Locale(language, country);

        messages = ResourceBundle.getBundle("MessagesBundle", currentLocale);
        System.out.println(messages.getString("greetings"));
        System.out.println(messages.getString("inquiry"));
        System.out.println(messages.getString("farewell"));
    }
}

这显然有效,但我有几个类(目前不在一个包中)。 我是否需要在所有这些类中加载相同的包才能使用它们?

我想最终得到的是,在程序的开头,让用户选择他们想要使用的语言(从可用的.properties文件列表中),让他们输入一个将加载的命令具体文件。

这可能吗?

谢谢

您可以使用getString方法的公共静态方法创建一个帮助器类。 就像是:

public class Messages {
    private static Locale locale;

    public static void setLocale(Locale locale) {
        Messages.locale = locale;
    }

    public static String getString(String key) {
        return ResourceBundle.getBundle("MessagesBundle", locale).getString(key);
    }
}

设置消息的区域设置后,您可以通过以下方式获取消息

Messages.getString("greetings");

似乎没有任何理由为什么所有类都无法共享相同的LocaleResourceBundle 我假设即使您的类不在同一个包中,您也可以在同一个应用程序中使用它们。 您只需要公开它们或提供公共吸气剂。 例如:

public class YourClass {

    private static Locale currentLocale;
    private static ResourceBundle messages;

    static public void main(String[] args) {

        String language;
        String country;

        if (args.length != 2) {
            language = new String("en");
            country = new String("US");
        } else {
            language = new String(args[0]);
            country = new String(args[1]);
        }

        currentLocale = new Locale(language, country);

        messages = ResourceBundle.getBundle("MessagesBundle", currentLocale);
    }

    public static Locale getCurrentLocale() {
        return currentLocale;
    }

    public static ResourceBundle getMessages() {
        return messages;
    }
}

在其他课程中,您可以致电:

Locale currentLocale = YourClass.getCurrentLocale();
ResourceBundle messages = YourClass.getMessages();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM