Reputation: 331
I'd need to obtain all the objects created by a class. Is there any pre-built method to do this in Java API?
Upvotes: 2
Views: 147
Reputation: 66223
No. There is nothing in the standard language nor standard API to help you. Your only chance is to restrict your problem to some domain which is completely under your control. Then you can use some kind of reference tracking either by a factory or directly in the constructor.
Be careful though: A naive implementation will keep references to all objects forever and this will spoil garbage collection. java.lang.ref.Reference<T>
and associated stuff might help here. But frankly - this is not stuff for beginners.
Upvotes: 1
Reputation: 82559
It's not built into the API because there's no such thing as "created by an object" in terms of Java. You could use a cache for this. But it's not built into Java. You'd have to maintain this. You can save yourself some trouble by using Factory methods so you don't forget to store it in the cache.
class Creator {
Set<Stuff> set = new HashSet<Stuff>();
// each time you create an object, do this
void foo() {
Stuff stuff = // what you create
set.put(stuff);
}
// you get them like
Set<Stuff> objectsCreatedByThis() { return Collections.unmodifiableSet(stuff); }
}
One thing to be concerned about is that this will cause a high potential for memory leaks. You could use WeakReferences to get around this, so that when every other thread loses access to the Object, so does the set. After all, you wouldn't want your set to just store everything so it never gets GC'd.
Upvotes: 2