Java中的语言环境 setDefault() 方法及示例
Java中Locale 类的setDefault(Locale newLoc)方法用于为 JVM 或Java虚拟机的该实例设置默认语言环境,这绝不会影响主机语言环境。
句法:
public static void setDefault(Locale newLoc)
参数:该方法采用一个 Locale 类型的参数newLoc ,它指的是要设置的新的默认 Locale。
返回值:该方法不返回任何值。
异常:该方法可以抛出异常,例如-
- 如果安全管理器存在并且其 checkPermission 方法不允许该操作,则会引发 SecurityException。
- 如果 newLoc 为 null,则抛出 NullPointerException
下面的程序说明了 Locale 类的 setDefault() 方法:
示例 1:
// Java code to illustrate hashCode() method
import java.util.*;
class Locale_Demo {
public static void main(String[] args)
{
// Creating a new locale
Locale first_locale
= new Locale("nu", "NO", "NY");
// Displaying first locale
System.out.println("First Locale: "
+ first_locale);
// Setting the Locale
Locale.setDefault(new Locale("ar", "SA"));
Locale new_locale = Locale.getDefault();
// Displaying the hash_code of new locale
System.out.println("The Hash Code: "
+ new_locale);
}
}
输出:
First Locale: nu_NO_NY
The Hash Code: ar_SA
示例 2:
// Java code to illustrate hashCode() method
import java.util.*;
class Locale_Demo {
public static void main(String[] args)
{
// Creating a new locale
Locale first_locale
= new Locale("en", "In");
// Displaying first locale
System.out.println("First Locale: "
+ first_locale);
// Setting the Locale
Locale.setDefault(new Locale("en", "GB"));
Locale new_locale = Locale.getDefault();
// Displaying the hash_code of new locale
System.out.println("The Hash Code: "
+ new_locale);
}
}
输出:
First Locale: en_IN
The Hash Code: en_GB
参考: https: Java Java.util.Locale)