Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 252
Michael Ekstrand Avatar asked Mar 08 '13 23:03

Michael Ekstrand


People also ask

What is toString () method in Java?

Java - toString() Method The method is used to get a String object representing the value of the Number Object. If the method takes a primitive data type as an argument, then the String object representing the primitive data type value is returned.

Do all classes have toString in Java?

This is how every class has a toString() method: since Object has a toString() method, then 'children' of Object inherit a toString() method, the children of children of Object inherit a toString() method, and so on. So every class 'automatically' gets a toString() method by inheritance.

In which of the following classes toString () method is already overridden?

The default toString() method in Object prints “class name @ hash code”. We can override the toString() method in our class to print proper output. For example, in the following code toString() is overridden to print the “Real + i Imag” form.

What is the default implementation of toString in Java?

By default the toString() method will return a string that lists the name of the class followed by an @ sign and then a hexadecimal representation of the memory location the instantiated object has been assigned to.


1 Answers

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.

like image 152
barfuin Avatar answered Oct 10 '22 03:10

barfuin