• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

How to overrule the toString method.

 
Ranch Hand
Posts: 269
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,
For debugging purpose, I want to display the references of objects.
However, some of this objects have overload the toString method. As a result I get :
"Value : 1
Date : 12/02/02"
instead of
"Toto@1323b930".
I know it is possible to get the references of the object but I can't remember how.
Any help would be appreciate.
W.
 
Ranch Hand
Posts: 61
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I am guessing, but what about something like this?
String refNumber = ((Object)yourObject).toString();
I am guessing that if you cast any object to an (Object) you will force it to use the default toString() functionality.
I am just guessing.
Mark
 
author
Posts: 14112
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Well, you guessed wrong... The method is still invoked polymorphically, so that the type of the object will determine the actual method called, not the type of the reference (casting only affects reference types).
 
Sheriff
Posts: 9109
12
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You could do something like
if ( Object1 == Object2 ){ ...
to see whether the objects have the same reference or not.
 
Ranch Hand
Posts: 401
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Object's toString is:

But if hashCode is overriden, it won't help. In that case use System.identityHashCode:
 
Wilfried LAURENT
Ranch Hand
Posts: 269
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
It works! Thanks a lot Dave!
W.
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic