views:

81

answers:

4

I'm looking for a way to get all instantiated objects of a given type in Java.

With Ruby you can use the ObjectSpace.each_object method:

a = 102.7
b = 95.1
ObjectSpace.each_object(Numeric) {|x| p x }

would give

95.1
102.7
+1  A: 

There is no Java equivalent to this.

The only way you could do something like this in Java would be to have each class create and maintain a collection of all instances. IMO, that would be a bad idea, unless there are exceptional circumstances that justify the overheads. For a start, the "all instances" collection would need to be implemented in such a way as to avoid garbage retention.

Stephen C
JRuby doesn't support ObjectSpace.each_object (or at least they'd like not to support it) because Java itself doesn't support it, and implementing it by maintaining weak references is hurts efficiency greatly.
Ken Bloom
A: 

I don't know whether you can do this. An idea, though - is there a run-time interface to the garbage collector? The GC should be keeping track of all currently active objects. You could probably hook into it somehow to get this information, and use run-time inspection to determine what objects have the class you're looking for.

Claudiu
+1  A: 

This article might be worth a looksie. I stumbled on Java's Reflection API a little while ago and I quite like it. Every Java programmer I've talked to though says that it's the spawn of satan though.

If that doesn't make you want to learn it I don't know what will.

Chuck Vose
Nothing in the reflection APIs allow you to iterate over all instances of a class.
Stephen C
I stand corrected then
Chuck Vose
A: 

The Java Debug Interface (JDI) has new methods in Java 6.0 which allow tools written in Java itself to do some limited memory profiling. For example, the ReferenceType has an instances method which allows the tool to get a reference to all instances of the type.

See com.sun.jdi.ReferenceType.html#instances

Adrian