CodeQL 文档

使用默认 toString()

ID: java/call-to-object-tostring
Kind: problem
Security severity: 
Severity: recommendation
Precision: high
Tags:
   - reliability
   - maintainability
Query suites:
   - java-security-and-quality.qls

点击查看 CodeQL 代码库中的查询

在大多数情况下,在需要对象的字符串表示形式时,调用 java.lang.Object 中的 toString 的默认实现并非预期行为。默认 toString 方法的输出包括对象的类名以及对象的哈希码,这通常不是预期的结果。

此规则包括对解析为 java.lang.Object.toStringtoString 的显式和隐式调用,尤其是用于打印或日志语句的调用。

建议

对于要打印的对象,请为该对象定义一个 toString 方法,该方法返回人类可读的字符串。

示例

以下示例显示打印对象会隐式调用 toString。由于类 WrongPerson 没有 toString 方法,因此会改为调用 Object.toString,这会返回类名和 wp 对象的哈希码。

// This class does not have a 'toString' method, so 'java.lang.Object.toString'
// is used when the class is converted to a string.
class WrongPerson {
	private String name;
	private Date birthDate; 
	
	public WrongPerson(String name, Date birthDate) {
		this.name =name;
		this.birthDate = birthDate;
	}
}

public static void main(String args[]) throws Exception {
	DateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd");
	WrongPerson wp = new WrongPerson("Robert Van Winkle", dateFormatter.parse("1967-10-31"));

	// BAD: The following statement implicitly calls 'Object.toString', 
	// which returns something similar to:
	// WrongPerson@4383f74d
	System.out.println(wp);
}

相反,在以下示例的修改中,类 Person 确实具有 toString 方法,该方法返回一个字符串,其中包含在创建对象 p 时传递的参数。

// This class does have a 'toString' method, which is used when the object is
// converted to a string.
class Person {
	private String name;
	private Date birthDate;
	
	public String toString() {
		DateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd");
		return "(Name: " + name + ", Birthdate: " + dateFormatter.format(birthDate) + ")";
	}
	
	public Person(String name, Date birthDate) {
		this.name =name;
		this.birthDate = birthDate;
	}
}

public static void main(String args[]) throws Exception {
	DateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd");
	Person p = new Person("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);
}

参考文献

  • J. Bloch,Effective Java(第二版),第 10 项。Addison-Wesley,2008 年。

  • Java API 规范:Object.toString().

  • ©2025GitHub,Inc.
  • 条款
  • 隐私