You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

用户输入国际电话号码时获取对应国家名称的Java实现方案咨询

你当前使用的是Google的libphonenumber库,可按以下方案扩展实现获取国家名称的功能:

实现逻辑

  • 调用PhoneNumberUtil提供的getRegionCodeForCountryCode()方法,将解析得到的数字国家代码转换为ISO 3166-1二位地区编码
  • 借助Java原生Locale类,将二位地区编码转换为对应国家的展示名称,支持自定义返回名称的语言类型

修改后完整代码

import com.google.i18n.phonenumbers.NumberParseException;
import com.google.i18n.phonenumbers.PhoneNumberUtil;
import com.google.i18n.phonenumbers.Phonenumber;
import java.util.Locale;
import java.util.Scanner;

public class PhoneCountryDemo {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter your phone no.:");
        String phone = sc.next();
        PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
        try{
            Phonenumber.PhoneNumber phoneNumber = phoneUtil.parse(phone, "");
            int countryCode = phoneNumber.getCountryCode();
            // 获取二位地区编码
            String regionCode = phoneUtil.getRegionCodeForCountryCode(countryCode);
            // 转换为中文国家名,如需英文改为Locale.ENGLISH即可
            String countryName = new Locale("", regionCode).getDisplayName(Locale.CHINA);
            // 按需求格式输出
            System.out.printf("+%d(%s)%n", countryCode, countryName);
        }
        catch(NumberParseException e){
            System.err.println("NumberParseException was thrown: " + e.toString());
        }
    }
}

注意事项

  • 对于同一国家代码对应多个地区的场景(比如+1同时对应美国、加拿大等),libphonenumber会自动根据完整手机号匹配最精准的地区编码,无需额外处理
  • 若需要自定义国家名称映射,可自行维护「国家代码-国家名称」的键值对映射表,解析到国家代码后直接查表即可

内容的提问来源于stack exchange,提问作者Abdul Haseeb

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 19:27:01