How to get ObjectID if you have toString() in class?

Hello!,

How can I know the ObjectID, if the class has toString().

Check following code.

How can I get the ObjectID of the object of classpqr.

class abc{

publicstaticvoid main(String args[]){

//This will print ObjectID of the object.

System.out.println((new xyz()));

//This will call toString method of the class.

System.out.println((new pqr()));

}

}

/**

* A class without toString method.

*/

class xyz{

}

/**

* A class with toString method.

*/

class pqr{

public String toString(){

return"ChetanParekh";

}

}

Reg,

Chetan

[1438 byte] By [someone_geniusa] at [2007-9-30 23:58:51]
# 1

"ObjectID"? I may be wrong but I think it's up the JVM how to deal with issues like this.The default response from toString doesn't have to be what it usually is, and isn't guaranteed to have any meaning.

You can't do pointer arithmetic in Java, if that's what you're hoping for.

But check out System.identityHashCode. That plus getClass.getName plus an @ plus formatting as hex will get the string you want.

paulcwa at 2007-7-7 15:43:00 > top of Java-index,Java Essentials,Java Programming...
# 2
Object#toString:public String toString() {return getClass().getName() + "@" + Integer.toHexString(hashCode());}
levi_ha at 2007-7-7 15:43:00 > top of Java-index,Java Essentials,Java Programming...
# 3
The hashCode() can be overriden too.You need to use System.identityHashCode(Object)
Peter-Lawreya at 2007-7-7 15:43:00 > top of Java-index,Java Essentials,Java Programming...
# 4

That depends on what OP wants, I guess. What I got from his first post is that he wants to have a toString as if he hadn't overridden it. If there is a custom hash code, then Object#toString will print that. That's why I showed him that method. Of course, if he wants the hash code as would be generated by Object, he should use identityHashCode.

levi_ha at 2007-7-7 15:43:00 > top of Java-index,Java Essentials,Java Programming...
# 5
> The hashCode() can be overriden too.> You need to use System.identityHashCode(Object)The only problem with using the System.identityHashCode method is that it is not guarenteed to be unique. matfud
matfuda at 2007-7-7 15:43:00 > top of Java-index,Java Essentials,Java Programming...