Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validating BCP-47 language tag using Java APIs

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?

like image 938
SerCe Avatar asked Jul 04 '26 22:07

SerCe


1 Answers

Coming late to this question, but now you can use BCP47J, a Java library that provides several functions related to BCP47 language tags.

like image 172
Rodolfo M. Raya Avatar answered Jul 06 '26 12:07

Rodolfo M. Raya