9

sometimes printf("%p", this) helps to see different instances.

What's the equivalent of that in android?
(to print out address of this variable or something unique(it may not be address) to the instance)

It seems I can new interface like OnTouchListener then, how do I print something to differentiate the different instances of them?

4

2 回答 2

11

Something like this should do it:

android.util.Log.i("Instance", "This is: " + this);

By default, the toString implementation of Object will print the class type plus a hash code which can be considered somewhat equivalent to the this pointer in C++.

The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character '@', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:

getClass().getName() + '@' + Integer.toHexString(hashCode())

If an object provides a different implementation of toString(), like for instance String does, then you can use the above canonical implementation of the base toString() method to get the same results.

于 2012-12-27T05:25:00.240 回答
1

To get something distinct to the instance, you should use System.identityHashCode(this). It returns what the default implementation of .hashCode() in Object returns (which may have been overridden in subclasses, so that's why you shouldn't use .hashCode() directly), which, according to the documentation, is "As much as is reasonably practical" distinct for distinct objects.

于 2012-12-27T08:54:30.397 回答