Java中的 Locale.Builder setVariant() 方法及示例
Java中Java .util.Locale.Builder 类的setVariant(String)方法用于将此 Locale.Builder 设置为指定的变体。这意味着此方法将设置 Locale.Builder 实例的当前变体以匹配提供的变体并返回它。如果指定的变体为 null 或为空,则移除此 LocaleBuilder 的变体。根据 IETF BCP 47 变体子标签的语法要求检查指定的变体,然后将其标准化为小写。
句法:
public Locale.Builder setVariant(String variant)
参数:此方法接受变体作为参数,该参数是要设置为此 Locale.Builder 实例的字符串。
返回值:此方法返回一个Locale.Builder 实例,其中包含此 Locale.Builder 的变体集到指定的变体。
异常:此方法抛出以下异常:
- IllformedLocaleException : 如果指定的变体有任何格式错误的字段
方案一:
// 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 variant of Locale.Builder
String variant
= (new Locale("nu", "NO", "NY"))
.getDisplayVariant();
System.out.println("Setting the variant: "
+ variant);
localeBuilder
= localeBuilder.setVariant(variant);
// Displaying Locale.Builder
System.out.println("Updated LocaleBuilder: "
+ localeBuilder);
}
}
输出:
LocaleBuilder: java.util.Locale$Builder@232204a1
Setting the variant: Nynorsk
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 variant of Locale.Builder
String variant = "asdasf@!vsd#";
System.out.println("Setting the variant: "
+ variant);
try{
localeBuilder
= localeBuilder.setVariant(variant);
// Displaying Locale.Builder
System.out.println("Updated LocaleBuilder: "
+ localeBuilder);
}
catch(Exception e)
{
System.out.println(e);
}
}
}
输出:
LocaleBuilder: java.util.Locale$Builder@232204a1
Setting the variant: asdasf@!vsd#
java.util.IllformedLocaleException:
Ill-formed variant:
asdasf@!vsd# [at index 0]
参考: https://docs.oracle.com/javase/9/docs/api/ Java/util/Locale.Builder.html#setVariant-java.lang.String-