1. 概述

在本文中,我们将介绍在 Groovy 中将 String 转换为 Integer 的多种方法。这类转换在日常开发中非常常见,比如处理用户输入、解析配置或接口参数时。掌握这些方式不仅能提升编码效率,还能避免踩坑 ❌。

2. 使用 as 关键字进行类型转换

Groovy 提供了简洁的 as 关键字来进行类型转换,其底层实际上是调用目标类型的 asType() 方法。

✅ 示例:将字符串转为 Integer

def "givenString_whenUsingAsInteger_thenConvertToInteger"() {
    given:
    def invalidString = "123a"
    Integer integerNum = "123" as Integer

    when:
    def intNum = invalidString?.isInteger() ? invalidString as Integer : null

    then:
    intNum == null
    integerNum == 123
}

你也可以直接转为原始类型 int

def "givenString_whenUsingAsInt_thenConvertToInt"() {
    given:
    int intNum = "123" as int

    expect:
    intNum == 123
}

⚠️ 注意:如果字符串包含非数字字符(如 "123a"),会抛出 NumberFormatException

3. 使用 toInteger() 方法

Groovy 扩展了 JDK 的 CharSequence 接口,提供了 toInteger() 方法,使用起来非常直观。

def "givenString_whenUsingToInteger_thenConvertToInteger"() {
    given:
    int intNum = "123".toInteger()

    expect:
    intNum == 123
}

📌 这是 Groovy 风格最推荐的方式之一,简洁且语义清晰。

4. 使用 Integer.parseInt()

这是 Java 原生的方式,也是最广为人知的方法之一。在 Groovy 中同样可以直接使用。

def "givenString_whenUsingParseInt_thenConvertToInteger"() {
    given:
    int intNum = Integer.parseInt("123")

    expect:
    intNum == 123
}

✅ 优点:性能好、语义明确
❌ 缺点:遇到非法字符或 null 会直接抛异常

5. 使用 Integer#intValue()

这种方式是先通过 Integer.valueOf() 创建一个 Integer 对象,再调用其 intValue() 转为基本类型。

def "givenString_whenUsingIntValue_thenConvertToInteger"() {
    given:
    int intNum = Integer.valueOf("123").intValue()

    expect:
    intNum == 123
}

或者更简洁地直接获取对象:

def "givenString_whenUsingNewInteger_thenConvertToInteger"() {
    given:
    Integer intNum = Integer.valueOf("123")

    expect:
    intNum == 123
}

⚠️ 注意:new Integer(string) 已被标记为过时,推荐使用 Integer.valueOf()

6. 使用 Integer.valueOf()

parseInt() 类似,但返回的是 Integer 包装类对象,适用于需要自动装箱的场景。

def "givenString_whenUsingValueOf_thenConvertToInteger"() {
    given:
    int intNum = Integer.valueOf("123")

    expect:
    intNum == 123
}

📌 小贴士:valueOf() 在处理小整数时会缓存对象,性能更优。

7. 使用 DecimalFormat

如果你需要处理带格式的数字字符串(例如 "1,234"),可以使用 DecimalFormat

def "givenString_whenUsingDecimalFormat_thenConvertToInteger"() {
    given:
    DecimalFormat decimalFormat = new DecimalFormat("#")

    when:
    int intNum = decimalFormat.parse("123").intValue()

    then:
    intNum == 123
}

📌 适用场景:

  • 处理千分位分隔符
  • 格式化输入数据
  • 国际化数字格式解析

但对纯数字字符串来说略显“杀鸡用牛刀”。

8. 异常处理与安全转换

这是最容易踩坑的部分 ⚠️。以下情况会抛出异常:

  • 字符串包含非数字字符 → NumberFormatException
  • 字符串为 nullNullPointerException

示例:非法字符串触发异常

def "givenInvalidString_whenUsingAs_thenThrowNumberFormatException"() {
    given:
    def invalidString = "123a"

    when:
    invalidString as Integer

    then:
    thrown(NumberFormatException)
}

示例:null 字符串导致空指针

def "givenNullString_whenUsingToInteger_thenThrowNullPointerException"() {
    given:
    def invalidString = null

    when:
    invalidString.toInteger()

    then:
    thrown(NullPointerException)
}

✅ 安全转换方案

为了避免异常,建议先使用 isInteger() 判断合法性:

def "givenString_whenUsingIsInteger_thenCheckIfCorrectValue"() {
    given:
    def invalidString = "123a"
    def validString = "123"

    when:
    def invalidNum = invalidString?.isInteger() ? invalidString as Integer : false
    def correctNum = validString?.isInteger() ? validString as Integer : false

    then:
    !invalidNum
    correctNum == 123
}

📌 推荐模式:

String input = params.userId
Integer userId = input?.isInteger() ? input.toInteger() : null

这样既安全又简洁,适合生产环境。

9. 总结

方法 是否推荐 说明
as Integer Groovy 风格,但需注意异常
toInteger() ✅✅ 最推荐,Groovy 特有扩展
Integer.parseInt() Java 原生,性能好
Integer.valueOf() 返回包装类,适合泛型场景
new DecimalFormat() ⚠️ 仅用于格式化字符串
直接强转 不推荐,易出错

最佳实践建议:

  1. 优先使用 toInteger(),代码最简洁
  2. 若需兼容 null 或非法输入,务必先用 ?.isInteger() 判断
  3. 对性能敏感的场景可用 parseInt(),但要做好 try-catch
  4. 避免使用已废弃的 new Integer(string)

所有示例代码均可在 GitHub 获取:https://github.com/eugenp/tutorials/tree/master/core-groovy-modules/core-groovy


原始标题:Convert String to Integer in Groovy