1

I've got a class running on a Android wearable which and there is supposed to be only one instance of it, however I'm very occasionally observing some unexpected behavior which is leading me to speculate if under some circumstances perhaps two instances are being created.

If I was in the C or C++ world I would just add logging statements to the class's methods to log the object's memory address of itself and it would be straightforward to check if there are actually two objects or just one.

What's a Java/Android equivalent way of being able to identify a particular object instance?

Gruntcakes
  • 37,738
  • 44
  • 184
  • 378
  • 1
    @Blackbelt: No, that's not what's being asked for at all. – Jon Skeet Feb 27 '15 at 22:30
  • You can use Singleton pattern in order to prevent multiple instances running. If you still insist on tracking objects, you can hash the current time milli second in constructor. – zawhtut Feb 27 '15 at 22:34
  • If your class does not override `hashCode()` (as it sounds like it has no reason to do), then you can reasonably expect that method to return different values for different instances. – John Bollinger Feb 27 '15 at 22:34
  • 1
    and if it does override `hashCode`, http://stackoverflow.com/a/909861/1864688 – guest Feb 27 '15 at 22:35
  • Note, too, that the Singleton pattern cannot be 100% effective in preventing multiple instances. For one thing, you can have up to one instance *per ClassLoader* with the standard Singleton implementation, and for another, under some circumstances you could obtain multiple instances via serialization. – John Bollinger Feb 27 '15 at 22:40
  • I've never used this but have you tried SomeClass.class.getDeclaredClasses() ? Returns an array containing Class objects for all classes, interfaces, enums and annotations that are members of this class. – mthomas Feb 27 '15 at 22:50

2 Answers2

3

The default implementation of toString() should do the trick. According to the java docs, it returns getClass().getName() + '@' + Integer.toHexString(hashCode()), and hashCode() should be unique to the instance, unless overridden in such a way that it isn't. According to the java docs, it seems the default implementation of hashCode() uses the object's memory address, offering functionality similar to what you mentioned in C or C++.

If hashCode() has been overridden, you could use System.identityHashCode(Object) which returns the unique hash code whether or not hashCode() has been overridden. More info here.

bmat
  • 2,084
  • 18
  • 24
1

You could use System.identityHashCode(obj);

See: http://developer.android.com/reference/java/lang/System.html#identityHashCode(java.lang.Object)

Erik Živković
  • 4,867
  • 2
  • 35
  • 53