As far as I know, the only way to validate whether a given BCP-47 language tag is valid is to use the following idiom:
private static boolean isValid(String tag) {
try {
new Locale.Builder().setLanguageTag(tag).build();
return true;
} catch (IllformedLocaleException e) {
return false;
}
}
However, the downside of this approach is that setLanguageTag
throws an exception which has noticeable (in a profile) performance overhead in workloads where locales are checked often.
The setLanguageTag
function is implemented using sun.util.locale
APIs, and as far as I can tell it's the only place where sun.util.locale.ParseStatus
is checked.
What I would like to be able to do is to use a method which has the following semantics:
import sun.util.locale.LanguageTag;
import sun.util.locale.ParseStatus;
private static boolean isValid(String tag) {
ParseStatus sts = new ParseStatus();
LanguageTag.parse(tag, sts);
return !sts.isError();
}
However, it's not possible to check the locale in the above way since it's using sun.*
classes directly since it requires additional JDK options to export sun.util.locale
from the java.base
module.
Is there a way to validate a language tag without using private sun.*
APIs while being consistent with the implementation of sun.util.locale.LanguageTag#parse
?