Movatterモバイル変換


[0]ホーム

URL:


CodeQL documentation
CodeQL resources

Use of default toString()

ID: java/call-to-object-tostringKind: problemSecurity severity: Severity: recommendationPrecision: highTags:   - quality   - reliability   - correctnessQuery suites:   - java-security-and-quality.qls

Click to see the query in the CodeQL repository

In most cases, calling the default implementation oftoString injava.lang.Object is not what is intended when a string representation of an object is required. The output of the defaulttoString method consists of the class name of the object as well as the object’s hashcode, which is usually not what was intended.

This rule includes explicit and implicit calls totoString that resolve tojava.lang.Object.toString, particularly calls that are used in print or log statements.

Recommendation

For objects that are printed, define atoString method for the object that returns a human-readable string.

Example

The following example shows that printing an object makes an implicit call totoString. Because the classWrongPerson does not have atoString method,Object.toString is called instead, which returns the class name and thewp object’s hashcode.

// This class does not have a 'toString' method, so 'java.lang.Object.toString'// is used when the class is converted to a string.classWrongPerson{privateStringname;privateDatebirthDate;publicWrongPerson(Stringname,DatebirthDate){this.name=name;this.birthDate=birthDate;}}publicstaticvoidmain(Stringargs[])throwsException{DateFormatdateFormatter=newSimpleDateFormat("yyyy-MM-dd");WrongPersonwp=newWrongPerson("Robert Van Winkle",dateFormatter.parse("1967-10-31"));// BAD: The following statement implicitly calls 'Object.toString',// which returns something similar to:// WrongPerson@4383f74dSystem.out.println(wp);}

In contrast, in the following modification of the example, the classPerson does have atoString method, which returns a string containing the arguments that were passed when the objectp was created.

// This class does have a 'toString' method, which is used when the object is// converted to a string.classPerson{privateStringname;privateDatebirthDate;publicStringtoString(){DateFormatdateFormatter=newSimpleDateFormat("yyyy-MM-dd");return"(Name: "+name+", Birthdate: "+dateFormatter.format(birthDate)+")";}publicPerson(Stringname,DatebirthDate){this.name=name;this.birthDate=birthDate;}}publicstaticvoidmain(Stringargs[])throwsException{DateFormatdateFormatter=newSimpleDateFormat("yyyy-MM-dd");Personp=newPerson("Eric Arthur Blair",dateFormatter.parse("1903-06-25"));// GOOD: The following statement implicitly calls 'Person.toString',// which correctly returns a human-readable string:// (Name: Eric Arthur Blair, Birthdate: 1903-06-25)System.out.println(p);}

References

  • J. Bloch,Effective Java (second edition), Item 10. Addison-Wesley, 2008.

  • Java API Specification:Object.toString().


[8]ページ先頭

©2009-2025 Movatter.jp