0

I am writing a sort of framework for Android. Other developers are able to extend this Framework with their Plugins.

Currently, to add a new Plugin, one needs to

a) write a new class which has to extend class AbstractPlugin (which is written by me)
b) For each plugin, my code needs to do some initialization. Thus one also, in one place inside the Framework, needs to increment 1 constant and add a new line of code like this:

ArrayList<AbstractPlugin> plugins = new ArrayList<>[3] // increment this 

plugin[0] = new PluginBlah();
plugin[1] = new PluginShowStars();
plugin[2] = new PluginBlurSurface(); 
// here add a new line initializing plugin[N] with the Plugin you've just written
(...)

for(int i=0; i<plugins.size(); i++)
  plugin[i].initalize();

The need to do the above leaves a bad taste in my mouth. I am thinking my Framework should be able to self-discover. Can my code somehow discover all classes which extend AbstractPlugin (all of them must belong to the same package like AbstractPlugin) and initialize itself?

EDIT:
I don't feel this is a duplicate of the 2 questions (I have read them both before), because both of them deal with generic Java and give as an accepted answer the 'ServiceLoader' mechanism, which doesn't work in Android.

Leszek
  • 1,181
  • 1
  • 10
  • 21
  • Mb mark them with annotation? – deathangel908 Jun 16 '17 at 21:01
  • You can use reflection to pick out all classes that are instances of `AbstractPlugin` from the classpath or a given package – OneCricketeer Jun 16 '17 at 21:02
  • I don't like the idea with getting all subclasses, user should decide which classes he's willing to init in plugin, which not, search for classes that marked with annotation seems like the better choice (of course you need reflection for that as well). E.g. android doesn't register all children of activities, you need to specify them in manifest. What if you decide to extend your framework, and there would be another base class. – deathangel908 Jun 16 '17 at 21:06
  • Annotations, huh? After a 5 min quick research it seems to me that in order to discover all annotated classes, I'd need to bring in some external dependencies? Standard Java itself cannot do it? If this is indeed the case, this seems hardly better than having your users add a line of code and increment a constant... – Leszek Jun 16 '17 at 21:21

0 Answers0