数据类型
- Sonar提示: Use "BigDecimal.valueOf" instead.
解决方法:使用BigDecimal.valueOf()代替。因为这个方法内部会将参数转换为String,保证精度不丢失。
public static BigDecimal valueOf(double val) {
return new BigDecimal(Double.toString(val));
}
- Sonar提示: Equality tests should not be made with floating point values.
解决方法: 浮点数不应该用==去比较,可能会精度丢失导致不准确。
使用BigDecimal.valueOf().compareTo()比较。如果为零可以直接使用BigDecimal.ZERO。
if (BigDecimal.valueOf(value1).compareTo(BigDecimal.valueOf(value2)) == 0) {
//....
}
如果是double类型,也可以直接用Double.doubleToLongBits()的结果值用==,>,<进行比较,如下:
if(Double.doubleToLongBits(d1) == Double.doubleToLongBits(d2))){
//
}
- Sonar提示: Cast one of the operands of this subtraction operation to a "double".
解决方法:使用(double)类型转换,再进行运算。
double d = (double)a + (double)b;
- Sonar提示: Cast one of the operands of this multiplication operation to a "long".
解决方法:在数字后面加上L转换类型。
60*1000*60L;
修饰符
- Sonar提示: Make this "public static " field final .
解决方法:添加final,或者改成 protected。
如果使用了"public static " 最好加上final,避免多个对象都修改了变量造成错误。
Sonar解释如下:There is no good reason to declare a field "public" and "static" without also declaring it "final". Most of the time this is a kludge to share a state among several objects. But with this approach, any object can do whatever it wants with the shared state, such as setting it to null。
- Sonar提示: Cannot assign a value to final variable ""
解决方法:final修饰的变量不可赋值,去掉final修饰符或赋值语句。
- Sonar提示: SonarLint: Format specifiers should be used instead of string concatenation.
解决方法: 使用格式说明符。
String.format("字符串其他内容 %s 字符串其他内容", data)
方法
- Sonar提示: Return an empty collection instead of null.
解决方法: 返回空集合而不是返回null,空集合不会导致空指针异常。
return Collections.emptyList();
实体类(model)
- Sonar提示: This class overrides "equals()" and should therefore also override "hashCode()".
解决方法: 重写equals()必须重写hashCode()。IDEA可以通过Alt+Insert自动生成。
异常
- Sonar提示: Use a logger to log this exception.
解决方法:logger.error("错误提示字符串:",e);
- Sonar提示: Define and throw a dedicated exception instead of using a generic one.
解决方法:不要直接抛Error,RuntimeException/Throwable/Exception这样的通用的异常,使用更具体的异常代替
- Sonar提示: Either log or rethrow this exception.
解决方法: logger.error("错误提示字符串:",e);
集合
- Sonar提示: Iterate over the "entrySet" instead of the "keySet".
解决方法: 使用entrySet,然后再通过entrySet获取key。
for (Map.Entry<String, String> entry : map.entrySet()) {
String key=entry.getKey();
String value=entry.getValue();
}