简体   繁体   English

Java为什么不公开基于toString / hashCode / equals的编译时反射?

[英]Why doesn't Java expose a Compile time reflection based toString/hashCode/equals?

If I understand it correct, it should cost nothing in addition to actual function processing (of toString/hashCode/equals), if Java could compute the functions for the object for which compile-time reflection is requested. 如果我理解正确,那么如果Java可以为需要编译时反射的对象计算函数,那么除了实际的函数处理(toString / hashCode / equals)之外,它应该不花任何费用。

For the cases when objects are up/down casted the behavior is still better than pointer address as toString representation, which practically is useless. 对于上/下转换对象的情况,其行为仍优于指针地址作为toString表示,这实际上是没有用的。

Something like 就像是

// Returns the compile time 'ReflectionToStringBuilder.toString(foo)'
foo.tryToString()

What am I missing ? 我想念什么?

Replying a comment I found correct words to my question. 回复评论后,我发现我的问题的正确词。

Why do we have to hand code (/eclipse generated) toString/hash/equals which could have been done by Java compiler ? 为什么我们必须将Java编译器可以完成的代码(/ eclipse生成)传递给String / hash / equals?

  1. Java is a very conservative language, to change the default behaviour after 20 years would change existing programs. Java是一种非常保守的语言,如果20年后更改默认行为,则会更改现有程序。 Which is something that is generally avoided in Java as much as possible. 通常,在Java中通常会避免这种情况。
  2. If toString was to always return the value of every field then it opens a program up to two risks, a) the generated string could get very large, ie spam logs and b) get so so large due to a circular reference or big data that it would never end and cause a stack overflow or an out of memory exception (both can be avoided, by adding extra cost/complexity). 如果toString总是返回每个字段的值,那么它将打开一个程序,该程序有两个风险:a)生成的字符串可能非常大,例如,垃圾邮件日志; b)由于循环引用或大数据而变得如此之大。它永远不会结束,并导致堆栈溢出或内存不足异常(可以通过增加额外的成本/复杂性来避免这两种情况)。
  3. defaulting to a hash is not useless, as a default behaviour in a debugger it gives clues about object identity rather than equality.. useful for certain classes of bug. 默认为哈希值并不是没有用的,因为它是调试器的默认行为,它提供了有关对象标识而不是相等性的线索。对于某些类的bug很有用。
  4. Some fields may contain sensitive information, such as passwords or credit card numbers. 一些字段可能包含敏感信息,例如密码或信用卡号。 Such fields should not appear in full in logs. 此类字段不应在日志中完整显示。 (chrylis) (chrylis)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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