10

有什么方法可以让 Eclipse 突出使用==运算符来测试字符串相等性?我一直错误地使用它而不是调用.equals().

我真的很想把它变成一个警告并需要一个@SuppressWarnings注释来删除它,在尚未发生的情况下,我实际上想比较字符串是否相等。

有没有什么工具可以帮助我在编辑时改掉这个坏习惯?

4

3 回答 3

11

使用静态分析工具,例如FindBugsPMDCheckStyle

每个都有 Eclipse 插件,以及 Ant 任务、Maven 插件等。

其中每一个都有与字符串相等相关的规则(Findbugs 规则PMD 规则Checkstyle 规则)。

于 2010-07-13T13:09:04.873 回答
5

已经给出了对该问题的明显答案,但这里有一个不是直接答案的警告:obj.equals如果 obj 为空,也可能会失败。所以你经常不得不使用这样的代码:

if(mystr1 != null && mystr1.equals(mystr2))

因为这

if(mystr1.equals(mystr2))

如果 mystr1 为 null,则会失败并返回 NullPointerException。

这就是为什么当比较字符串是已知常量时,经常使用以下语法:

if("ABCDEF".equals(mystr1))

而不是

if(mystr1.equals("ABCDEF"))

出于这个原因,许多库(如apache commons / lang)提供了结合这些检查的实用功能:

// this is the definition of org.apache.commons.lang.StringUtils.equals(String, String)
public static boolean equals(String str1, String str2) {
    return str1 == null ? str2 == null : str1.equals(str2);
}

// this is the definition of  org.apache.commons.lang.ObjectUtils.equals(Object, Object)
public static boolean equals(Object object1, Object object2) {
    if (object1 == object2) {
        return true;
    }
    if ((object1 == null) || (object2 == null)) {
        return false;
    }
    return object1.equals(object2);
}

使用这些方法通常比普通 equals 更安全,除非您确定这两个对象之一不为空

于 2010-07-13T14:49:18.320 回答
1

我不同意以前的答案 - 这是 eclipse 中的一个错误,你可以在这里投票:https ://bugs.eclipse.org/bugs/show_bug.cgi?id=39095 。

当您比较字符串时,Eclipse 可以很好地警告==您,因为这很少是您想要的(或原始作者想要的)。

于 2013-11-21T14:49:32.137 回答