编程语言
首页 > 编程语言> > java – 这是一个真正的警告还是过于敏感的lint?

java – 这是一个真正的警告还是过于敏感的lint?

作者:互联网

我有这个方法:

private Boolean compare(String property, String relationOperator,
        String operand) {
    Integer propertyValue = NumberUtils.toInt(property);
    Integer operandValue = NumberUtils.toInt(operand);

    switch (relationOperator)
    {
        case "<":  return propertyValue.compareTo(operandValue) < 0;
        case "<=": return propertyValue.compareTo(operandValue) <= 0;
/*WARN*/case "=":  return propertyValue.compareTo(operandValue) == 0;
        case ">=": return propertyValue.compareTo(operandValue) >= 0;
        case ">":  return propertyValue.compareTo(operandValue) > 0;
        case "!=": return propertyValue.compareTo(operandValue) != 0;
    }
    return Boolean.FALSE;
}

对于标记为/ * WARN * /的行,FindBugs 3.0.0告诉我:

Suspicious comparison of Integer references in
com.foo.MyClass.compare(String, String, String) [Scariest(1), High
confidence]

我认为代码没问题,因为我比较的是整数而不是整数,所以我可以安全地@SuppressWarnings在这一行吗?

解决方法:

你的代码是可怕的,因为它使用包装类,并且可以使用原语.此外,您的代码过于聪明.你应该尝试write dumb code.喜欢的东西,

private boolean compare(String property, String operator, String operand) {
    int pv = Integer.parseInt(property);
    int ov = Integer.parseInt(operand);
    if (operator.equals("<")) {
        return pv < ov;
    } else if (operator.equals("<=")) {
        return pv <= ov;
    } else if (operator.equals(">")) {
        return pv > ov;
    } else if (operator.equals(">=")) {
        return pv >= ov;
    } else if (operator.equals("!=")) {
        return pv != ov;
    } else if (operator.equals("=") || operator.equals("==")) {
        return pv == ov;
    }
    return false;
}

标签:java,findbugs
来源: https://codeday.me/bug/20190824/1713195.html