简体   繁体   English

验证Java类是否实现toString()

[英]Verify that Java classes implement toString()

As a part of the regular static analysis of my program, I would like to check that classes are likely to have sane toString() methods. 作为我的程序的常规静态分析的一部分,我想检查类可能有理智的toString()方法。 Probably not that every class implements them, but perhaps that no instantiable concrete class uses Object 's implementation of toString() . 可能不是每个类都实现它们,但也许没有可实例化的具体类使用ObjecttoString()

Is there a lint toolkit that checks for this? 是否有一个lint工具包来检查这个? The ones I currently use are FindBugs and CheckStyle; 我目前使用的是FindBugs和CheckStyle; I haven't found an obvious way to check using either of those. 我还没有找到一种明显的方法来检查其中任何一种。 I'm also looking at adding PMD to my lint suite, and would be open to something in Sonar as well. 我也在考虑将PMD添加到我的lint套件中,并且也可以在Sonar中使用它。 So I would prefer to do it using a tool already in my tool chest, but if I need to add yet another tool I will consider it. 所以我更喜欢使用工具箱中已有的工具来做,但如果我需要添加另一个工具,我会考虑它。

You can do this using the Checkstyle Regexp check: 您可以使用Checkstyle Regexp检查执行此操作:

<module name="Regexp">
    <property name="format" value="public\s+String\s+toString\s*()"/>
    <property name="message" value="All classes must implement toString()"/>
    <property name="ignoreComments" value="true"/>
</module>

This even recognizes commented-out toString() methods as not present. 这甚至可以将注释掉的toString()方法识别为不存在。 I tried it using Checkstyle 5.6 and eclipse-cs, but it should also work with earlier versions. 我尝试使用Checkstyle 5.6和eclipse-cs,但它也适用于早期版本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM