在 Eclipse 中使用相等运算符 (==) 进行字符串比较时突出显示
有什么方法可以让 Eclipse 突出显示使用 ==
运算符来测试字符串相等性吗?我一直错误地使用它而不是调用 .equals()
。
我真的很想把它变成一个警告,并需要一个 @SuppressWarnings 注释来删除它,在尚未发生的情况下,我实际上想比较字符串的对象相等性。
我可以使用任何工具来帮助我在编辑时改掉这个坏习惯吗?
Is there any way I can get Eclipse to highlight the use of the ==
operator to test String equality? I keep mistakenly using it instead of calling .equals()
.
I'd really like to make that into a warning and require an @SuppressWarnings
annotation to remove it, in the yet-to-happen case that I actually want to compare strings for object equality.
Are there any tools can I use to help break this bad habit at edit-time?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用静态分析工具,例如FindBugs、PMD 或 CheckStyle。
每个都有 Eclipse 插件,以及 Ant 任务、Maven 插件等。
每个插件都有与字符串相等相关的规则 (Findbugs 规则、PMD 规则、Checkstyle 规则)。
Use a static analysis tool such as FindBugs, PMD, or CheckStyle.
There are Eclipse plugins for each, along with Ant tasks, Maven plugins, etc.
Each of these has rules relating to String equality (Findbugs rule, PMD rule, Checkstyle rule).
问题的明显答案 已经给出了,但这里有一个警告,但不是直接答案:如果 obj 为 null,
obj.equals
也可能失败。因此,您经常必须使用这样的代码:因为
如果 mystr1 为 null,则会失败并出现 NullPointerException。
这就是为什么,当比较字符串是已知常量时,经常使用以下语法:
而不是
出于这个原因,许多库(如 apache commons / lang ) 提供了结合这些检查的实用函数:
使用这些方法通常比普通的 equals 更安全,除非您确定两个对象之一不为 null
The obvious answer to the question has already been given, but here is a warning that is not a direct answer:
obj.equals
can also fail if obj is null. So you'll often have to use code like this:because this
would fail with a NullPointerException if mystr1 is null.
Which is why, when the comparison string is a known constant, the following syntax is often used:
rather than
For this reason, many libraries (like apache commons / lang ) provide utility functions that combine these checks:
Using these methods is usually safer than plain equals, unless you know for sure that one of the two objects is not null
我不同意以前的答案 - 这是 Eclipse 中的一个错误,您可以在这里投票: https://bugs.eclipse.org/bugs/show_bug.cgi?id=39095。
当您将字符串与
==
进行比较时,Eclipse 可以很好地警告您,因为这很少不是您想要的(或者原始作者想要的)。I disagree with previous answers - it is a bug in eclipse and you can vote for it here : https://bugs.eclipse.org/bugs/show_bug.cgi?id=39095.
Eclipse can very well warn you when you compare Strings with
==
as this is seldom what you wanted (or what the original author wanted).