Java - 内部化问题

时间:2014-11-23 15:03:53

标签: java

为了使程序国际化,我获得了以下代码,允许我根据用户选择的内容使用多种语言。

import java.util.*; 
public class I18NSample { 
  static public void main(String[] args) { 
    String language, country; 
    if (args.length != 2) { // default is English-language
      language = new String("en"); country = new String("US"); 
    } else { 
      language = new String(args[0]); country = new String(args[1]);
    } 
    Locale currentLocale = new Locale(language, country); 
    ResourceBundle messages = 
      ResourceBundle.getBundle("MessagesBundle", currentLocale);   
    System.out.println(messages.getString("greetings"));
    System.out.println(messages.getString("inquiry")); 
    System.out.println(messages.getString("farewell")); 
  } 
}

这是我的MessagesBundle文件:

greetings = Hello.
farewell = Goodbye.
inquiry = How are you?

然而,当在我的程序中实现此代码时,我无法在其他类中使用messages.getString函数,并且我需要在main中使用此代码,因为它需要String []参数。有没有办法解决?

2 个答案:

答案 0 :(得分:2)

当然,只需将消息初始化移到您的课程上方并将其公开,如下所示:

import java.util.*; 
public class I18NSample { 
  public ResourceBundle messages;
  static public void main(String[] args) { 
    String language, country; 
    if (args.length != 2) { // default is English-language
      language = new String("en"); country = new String("US"); 
    } else { 
      language = new String(args[0]); country = new String(args[1]);
    } 
    Locale 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")); 
  } 
}

这样,您就可以使用I18NSample.ResourceBundle

从其他类访问它了

答案 1 :(得分:0)

所以你所拥有的不是国际化问题,而是代码结构问题。

您的messages变量是main方法的本地变量。将它作为类中的一个字段,然后在main中初始化它。

以下示例将向您展示我的意思。以类似的方式初始化您的Locale可能是有意义的。

import java.util.*; 

public class I18NSample { 

  private ResourceBundle messages; //this may have to be static to initialize it in main

  static public void main(String[] args) { 
    String language, country; 
    if (args.length != 2) { // default is English-language
      language = new String("en"); country = new String("US"); 
    } else { 
      language = new String(args[0]); country = new String(args[1]);
    } 
    Locale 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")); 
  } 

  //this getter exposes the ResourceBundle so you can use it outside of this class
  public ResourceBundle getMessages() { return messages; }
}
相关问题