开发者

Collection of objects of all classes which implement a particular interface

I have an interface TestInterface and different classes may implement the interface. Is it possible t开发者_开发问答o have a collection of all the objects which implements the interface? The collection can be created using

LinkedList<TestInterface> store

where store is the name of the collection. But how to keep track of the object creations of classes which implement the TestInterface. And moreover where to keep the collection?


Not knowing what you want this for, it's hard to tell.

But anyway, yes you can create a collection but in order to track and store references to the TestInterface objects, you must control their creation.

The easiest way would be to have a TestInterfaceFactory (see AbstractFactory pattern), this is also a good place to keep the store collection with the instance references.


Is it possible to have a collection of all the objects which implements the interface?

In theory yes.

In reality, it will only work if everything that creates an instance of the object also adds it to the list. And that probably makes it impractical ... unless you change the way the objects are created.

  • One approach use factories, but there is nothing to stop some code creating an instance without using your carefully implemented factory.

  • Another approach would be to replace the interface with an abstract base class whose constructor(s) guarantee that every new instance is added to the list. This can't be subverted using normal code. However, if you use Java Object Serialization (or similar) you'll need to put a "hook" into the base class to make sure that deserialized objects are added to the list.


Note that a collection that contains all instances of some interface or class is potentially a huge memory leak. You'll probably need to do something about this; e.g. using weak references.


If you desperately need to make this automatic, then in principle, you could:

  • use the Java instrumentation framework, adding a ClassFileTransformer to ensure that any class implementing your interface is redefined to have its constructors automatically add instances to your collection (look at something like the Bytecode Engineering Library, BCEL, if you were to go down this route);
  • possibly easier but still quite a lot of work: use the JVM Tool Interface to write an agent that can query the heap on the fly for instances of your object.

Either way, if the interface is yours, then introducing a programming convention whereby all instances of implementations of that interface are added to the collection is definitely easier, if more error-prone.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜