toLocale
is a LocaleUtils
class that is used to validate a locale string or a locale object.
There are two variations of the toLocale()
method.
This particular variation returns the passed locale if it’s non-null. Otherwise it returns the default locale.
public static Locale toLocale(final Locale locale)
This particular variation converts a locale string to a Locale
object. This variation strictly validates the input string. The language code must be lowercase, followed by an underscore and ending with the country code, which must be uppercase. The length must be correct. Examples of valid local strings are en_US
, hi_IN
, ja_JP
etc.
public static Locale toLocale(final String str)
LocaleUtils
The definition of LocaleUtils
can be found in the Apache Commons Lang package, which we can add to the Maven project by adding the following dependency to the pom.xml
file:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version>
</dependency>
For other versions of the commons-lang package, refer to the Maven Repository.
You can import the LocaleUtils
class as follows:
import org.apache.commons.lang3.LocaleUtils;
import org.apache.commons.lang3.LocaleUtils;import java.util.Locale;public class Main{public static void main(String[] args){// Example 1Locale locale = Locale.CHINA;System.out.println("The output of toLocale method for " + locale + " is " + LocaleUtils.toLocale(locale));// Example 2locale = null;System.out.println("The output of toLocale method for " + locale + " is " + LocaleUtils.toLocale(locale));// Example 3String localeString = "en_US";System.out.println("The output of toLocale method for " + localeString + " is " + LocaleUtils.toLocale(localeString));// Example 4localeString = "en_USA";System.out.println("The output of toLocale method for " + localeString + " is " + LocaleUtils.toLocale(localeString));}}
In the first example, the method returns the passed locale object because it is non-null.
In the second example, the method returns the default locale object because the passed locale object is null.
In the third example, the method returns the locale object for the country USA because the passed string denotes the locale of the USA.
In the fourth example, the method throws an example indicating that the format of the locale is invalid.
The output of toLocale method for zh_CN is zh_CN
The output of toLocale method for null is en_GB
The output of toLocale method for en_US is en_US
Exception in thread "main" java.lang.IllegalArgumentException: Invalid locale format: en_USA
at org.apache.commons.lang3.LocaleUtils.parseLocale(LocaleUtils.java:268)
at org.apache.commons.lang3.LocaleUtils.toLocale(LocaleUtils.java:348)
at Main.main(Main.java:22)
Free Resources