Locale Language Tag Roundtrip

Parse BCP 47 tags into Locale objects with forLanguageTag, build canonical tags back with Locale.Builder, and watch ill-formed tags resolve to und.

JavaConfig Management

Code

snippet
import java.util.Locale;

public class AcceptLanguageRouter {

    public static void main(String[] args) {
        // BCP 47 标签 -> Locale 对象
        for (String tag : new String[] {"en-US", "zh-CN", "pt-BR", "zh-Hant-TW"}) {
            Locale parsed = Locale.forLanguageTag(tag);
            System.out.println(tag + " -> " + parsed.getLanguage()
                    + "/" + parsed.getCountry()
                    + " (" + parsed.getDisplayLanguage(Locale.ENGLISH) + ")");
        }

        // Locale.Builder 按 language-script-region 规范顺序重组标签
        Locale rebuilt = new Locale.Builder()
                .setLanguage("zh")
                .setScript("Hant")
                .setRegion("TW")
                .build();
        System.out.println("rebuilt tag: " + rebuilt.toLanguageTag());

        // 语法非法的标签:解析失败得到 und(未确定),而不是抛异常
        Locale illFormed = Locale.forLanguageTag("en_**");
        System.out.println("invalid tag language: " + illFormed.getLanguage());
    }
}

How it works

Under the hood: the class AcceptLanguageRouter and the function main.

for (String tag : new String[] {"en-US", "zh-CN", "pt-BR", "zh-Hant-TW"}) is the loop that carries the per-item work. Resources are declared in a try-with-resources header, so they close on every exit path without a finally block.

Applying it

Running the file prints labeled results such as rebuilt tag:, invalid tag language: — each operation’s effect is visible in the output.

Statements that matter

Locale illFormed = Locale.forLanguageTag("en_**");
Locale parsed = Locale.forLanguageTag(tag);
Locale rebuilt = new Locale.Builder()
.setLanguage("zh")
.setScript("Hant")
.setRegion("TW")
.build();

Interactive Tools for This Topic

FAQ

What does Locale Language Tag Roundtrip print when run?
No setup needed: run the file and look for labeled lines like `rebuilt tag:`, `invalid tag language:` in the output.