Reputation: 19905
I would like to add some dynamic behavior to an application, preferably without resorting to reflection, so I am looking at object registration.
The approach I am thinking is simple: in a class (say Base
) which gets to be loaded early enough, a registry (e.g., a HashMap) of plugin objects will be maintained, each of which will later on be used for invoking some of their methods.
The question is, how to register those plugins in Base
without any prior knowledge of their existence (so that the application can be dynamically extended via more such plugins). Not knowing them beforehand means a ClassLoader
or any reference to their classes cannot be used, thus even with static initialization, registration code cannot be added (since the plugin classes will not be loaded early enough, so the Base
class will start executing without knowing them).
Is there any simple solution to the above scenario?
Upvotes: 0
Views: 1249
Reputation: 1986
could you use something like spring and dependency injection ? if you can, each plug in could be a initializing bean so its loaded on start up and in its init method call back to the base to register itself, if not through a direct dependency injection. that obviously uses reflection in background so not sure if that excludes this as your preferred solution...
on another note, typically, looking for classes is not fool proof esp if you could have multiple class loaders :-(
Upvotes: 0
Reputation: 160261
There's several ways of implementing plugin mechanisms, ultimately you need to either scan for implementations of an interface or annotations. Is it important to you that you implement this yourself? There's already libraries that do this (jspf for example).
If you're not interested in reflection, then the code must either adhere to a known interface. Otherwise you'll need to use reflection somewhere to map between what the plugin class(es) provide, and what the "base" code knows how to call.
Upvotes: 1