gpt4 book ai didi

java - 记录对象哈希码有用吗?

转载 作者:行者123 更新时间:2023-11-29 05:37:15 25 4
gpt4 key购买 nike

我在接手的项目中看到了很多这样的行:

log.debug(submitObject(" + object + ")");
log.debug(registerUser(" + user + ")");

等等。

在日志中打印出如下内容:

SubmitObject(java.lang.Object@13a317a)

仅记录对象类型及其哈希码是否有用?假设我想知道用户对象的名称,但我只有哈希码,我是否可以根据哈希码重建对象?

来自 object.toString() 的 javadoc

Returns a string representation of the object. In general, the toString method returns a string that "textually represents" this object. The result should be a concise but informative representation that is easy for a person to read. It is recommended that all subclasses override this method. The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:

getClass().getName() + '@' + Integer.toHexString(hashCode())
Returns: a string representation of the object.

我自己总是覆盖自定义对象的 toString() 以便它打印出对象的所有字段。我应该改为打印目标代码吗?

最佳答案

您可以使用 org.apache.commons 中的 ReflectionToStringBuilder,如果您无权访问源代码,或者如果您不想实现 toString 以更改现有代码.


例如:


如果 (LOGGER.isDebugEnabled()) {



 LOGGER.debug("用户:"
+ reflectionToStringBuilder.toString(用户,
ToStringStyle.MULTI_LINE_STYLE))

}

"LOGGER.isDebugEnabled() 非常重要,因为 toString 操作或 reflectionToStringBuilder 将在调用 log.debug 之前执行,因此您不希望进行如此昂贵的操作.

ReflectionToStringBuilderJavaDoc:http://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/builder/ReflectionToStringBuilder.html

关于java - 记录对象哈希码有用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19031256/

25 4 0