简体   繁体   中英

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.

For the cases when objects are up/down casted the behavior is still better than pointer address as toString representation, which practically is useless.

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 ?

  1. Java is a very conservative language, to change the default behaviour after 20 years would change existing programs. Which is something that is generally avoided in Java as much as possible.
  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).
  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.
  4. Some fields may contain sensitive information, such as passwords or credit card numbers. Such fields should not appear in full in logs. (chrylis)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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