Java中的 Locale.Builder setLocale(Locale) 方法及示例
Java中Java .util.Locale.Builder 类的setLocale(Locale)方法用于将此Locale.Builder 重置为指定的Locale。这意味着此方法将重置 Locale.Builder 实例的当前状态以匹配提供的 Locale 并返回它。
句法:
public Locale.Builder setLocale(Locale locale)
参数:此方法接受语言环境作为参数,该参数是要设置为此 Locale.Builder 实例的语言环境。
返回值:此方法返回一个Locale.Builder 实例,该实例是此 Locale.Builder 设置为指定 Locale 的状态。
异常:此方法抛出以下异常:
- IllformedLocaleException:如果指定的语言环境有任何格式错误的字段
- NullPointerException:如果指定的语言环境为 null
方案一:
// Java program to demonstrate
// the above method
import java.util.*;
import java.util.Locale.*;
public class LocaleBuilderDemo {
public static void main(String[] args)
{
// Creating a new Locale.Builder
Locale.Builder localeBuilder
= new Builder();
// Displaying Locale.Builder
System.out.println("LocaleBuilder: "
+ localeBuilder);
// setting the locale of Locale.Builder
Locale locale = Locale.FRANCE;
System.out.println("Setting the Locale: "
+ locale);
localeBuilder
= localeBuilder.setLocale(locale);
// Displaying Locale.Builder
System.out.println("Updated LocaleBuilder: "
+ localeBuilder);
}
}
输出:
LocaleBuilder: java.util.Locale$Builder@232204a1
Setting the Locale: fr_FR
Updated LocaleBuilder: java.util.Locale$Builder@232204a1
方案二:
// Java program to demonstrate
// the above method
import java.util.*;
import java.util.Locale.*;
public class LocaleBuilderDemo {
public static void main(String[] args)
{
// Creating a new Locale.Builder
Locale.Builder localeBuilder
= new Builder();
// Displaying Locale.Builder
System.out.println("LocaleBuilder: "
+ localeBuilder);
// setting the locale of Locale.Builder
Locale locale = Locale.ENGLISH;
System.out.println("Setting the Locale: "
+ locale);
localeBuilder
= localeBuilder.setLocale(locale);
// Displaying Locale.Builder
System.out.println("Updated LocaleBuilder: "
+ localeBuilder);
}
}
输出:
LocaleBuilder: java.util.Locale$Builder@232204a1
Setting the Locale: en
Updated LocaleBuilder: java.util.Locale$Builder@232204a1
参考: https://docs.oracle.com/javase/9/docs/api/ Java/util/Locale.Builder.html#setLocale-java.util.Locale-