在Eclipse中使用相等运算符(==)进行字符串比较时突出显示

Tom*_*sky 10 java eclipse equality suppress-warnings

有没有什么方法可以让Eclipse强调使用==运算符来测试String的相等性?我一直误用而不是打电话.equals().

我真的想把它变成一个警告并需要一个@SuppressWarnings注释去除它,在尚未发生的情况下,我实际上想比较字符串的对象相等性.

我是否可以使用任何工具来帮助在编辑时打破这种坏习惯?

mat*_*t b 11

使用静态分析工具,如FindBugs,PMDCheckStyle.

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

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


Sea*_*oyd 5

已经给出了问题的明显答案,但这里的警告不是直接答案:obj.equals如果obj为null,也会失败.所以你经常需要使用这样的代码:

if(mystr1 != null && mystr1.equals(mystr2))
Run Code Online (Sandbox Code Playgroud)

因为这

if(mystr1.equals(mystr2))
Run Code Online (Sandbox Code Playgroud)

如果mystr1为null,则会因NullPointerException而失败.

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

if("ABCDEF".equals(mystr1))
Run Code Online (Sandbox Code Playgroud)

而不是

if(mystr1.equals("ABCDEF"))
Run Code Online (Sandbox Code Playgroud)

出于这个原因,许多库(如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);
}
Run Code Online (Sandbox Code Playgroud)

除非您确定两个对象中的一个不为null,否则使用这些方法通常比plain equals更安全