0

ここでノブ。

コマンドラインベースのプログラムに国際化を実装しようとしています。以下は、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 ファイルのリストから) 選択できるようにすることです。特定のファイル。

これは可能ですか?

ありがとう

4

2 に答える 2

1

メソッドの public static メソッドを持つヘルパー クラスを作成できます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");
于 2013-10-30T15:27:47.963 に答える
1

Localeすべてのクラスが同じand を共有できなかった理由はないようですResourceBundle。クラスがすべて同じパッケージに含まれていなくても、同じアプリケーション内でそれらをすべて使用していると思います。それらを公開するか、公開ゲッターを提供するだけです。例えば:

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();
于 2013-10-30T15:37:34.937 に答える