简体   繁体   中英

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. Probably not that every class implements them, but perhaps that no instantiable concrete class uses Object 's implementation of toString() .

Is there a lint toolkit that checks for this? The ones I currently use are FindBugs and 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. 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:

<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. I tried it using Checkstyle 5.6 and eclipse-cs, but it should also work with earlier versions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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