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
"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.
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.