【问题标题】:new BigInteger(String) gives Sonar warningnew BigInteger(String) 给出声纳警告
【发布时间】:2018-06-05 08:17:25
【问题描述】:

我使用的是 IntelliJ IDEA 2018.1.3 Ultimate Edition,需要与表示为字符串的大整数(大到不适合 long,例如 20180531234240565494)进行比较:

public int compareNumeric(String compareTo) {
    return new BigInteger(version).compareTo(new BigInteger(compareTo));
}

这是here 提出的解决方案,我一直认为这是从String 创建BigInteger 的正确方法。

但是,IntelliJ 通过 Sonar 插件提供the following warning

不应使用构造函数来实例化“String”、“BigInteger”、“BigDecimal”和原始包装类

鱿鱼:S2129
绝不应使用 Strings、BigInteger、BigDecimal 的构造函数和用于包装原语的对象。与简单地在字符串的情况下使用所需的值并在其他所有情况下使用 valueOf 相比,这样做不太清楚并且使用更多的内存。
此外,这些构造函数在 Java 9 中已被弃用,这表明它们最终将完全从该语言中删除。

不合规代码示例

String empty = new String(); // Noncompliant; yields essentially "", so just use that.
String nonempty = new String("Hello world"); // Noncompliant
Double myDouble = new Double(1.1); // Noncompliant; use valueOf
Integer integer = new Integer(1); // Noncompliant
Boolean bool = new Boolean(true); // Noncompliant
BigInteger bigInteger = new BigInteger("1"); // Noncompliant
BigDecimal bigDecimal = new BigDecimal(1.1); // Noncompliant<br/>

合规解决方案

String empty = "";
String nonempty = "Hello world";
Double myDouble = Double.valueOf(1.1);
Integer integer = Integer.valueOf(1);
Boolean bool = Boolean.valueOf(true);
BigInteger bigInteger = BigInteger.valueOf(1);
BigDecimal bigDecimal = BigDecimal.valueOf(1.1);

首先,我没有看到 the constructor 在 Java 9 中被弃用,Sonar 在这里错了吗?

我是否进行了错误的比较并触发了误报,还是应该以其他方式进行比较?

我能想到的唯一其他方法是直接比较字符串,但这也会迫使我首先检查字符串是否为数字。

【问题讨论】:

  • BigInteger.valueOf() 的建议解决方案仅适用于可以适合 long 的值,所以我会忽略该警告(假设您的 Strings 代表不适合的值long)
  • @Stultuske 警告中提到这些构造函数已被弃用,但我没有看到 new BigInteger(String) 被弃用。
  • @Eran 或假设您的字符串不是常量,在这种情况下您不知道它包含什么值。
  • @Stultuske 它们在 Java 10 中也没有被弃用。它们甚至没有计划在Java 11 中被弃用。更有可能BigInteger 被错误地扔进了与IntegerLong 构造函数 弃用的同一锅中。
  • 顺便说一下,您的20180531234240565494 看起来有点像日期和时间字符串。你确定BigInteger 是在这里使用的最佳类型吗?

标签: java sonarqube biginteger


【解决方案1】:

您遇到了这个问题SONARJAVA-2740,该问题已在最新的 SonarJava 版本中得到修复,该版本应该会在几天内公开发布。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-10
    • 2022-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-22
    • 2022-01-14
    相关资源
    最近更新 更多