JDK Locale类处理希伯来语(他),意第绪语(yi)和印度尼西亚语(id)的ISO语言代码

Ale*_*ian 16 java locale

当实例化一个Locale用以下语言代码的任一对象:he,yi并且id它不保留自己的价值.

例如:

Locale locale = new Locale("he", "il");
locale.getLanguage(); // -> "iw"
Run Code Online (Sandbox Code Playgroud)

造成这种情况的原因是什么方法可以解决这个问题?

Ale*_*ian 19

Locale类不会对您在其中提供的内容进行任何检查,但会为其旧值交换某些语言代码.从文档:

ISO 639不是一个稳定的标准; 它定义的一些语言代码(特别是"iw","ji"和"in")已经改变.此构造函数接受旧代码("iw","ji"和"in")和新代码("he","yi"和"id"),但Locale上的所有其他API将仅返回旧代码.

这是构造函数:

public Locale(String language, String country, String variant) {
    this.language = convertOldISOCodes(language);
    this.country = toUpperCase(country).intern();
    this.variant = variant.intern();
}
Run Code Online (Sandbox Code Playgroud)

这是神奇的方法:

private String convertOldISOCodes(String language) { 
    // we accept both the old and the new ISO codes for the languages whose ISO 
    // codes have changed, but we always store the OLD code, for backward compatibility 
    language = toLowerCase(language).intern(); 
    if (language == "he") { 
        return "iw"; 
    } else if (language == "yi") { 
        return "ji"; 
    } else if (language == "id") { 
        return "in"; 
    } else { 
        return language; 
    }
}
Run Code Online (Sandbox Code Playgroud)

它创建的对象是不可变的,所以没有解决这个问题.该类也是final,因此您无法扩展它,并且它没有特定的接口来实现.使它保留这些语言代码的一种方法是在这个类周围创建一个包装器并使用它.

  • 有趣的是,'he`,`yi`和`id`是标准代码(根据维基百科 - http://en.wikipedia.org/wiki/List_of_ISO_639-1_codes),与他们的替代品不同. (3认同)