1

Neither interfaces nor abstract classes can dictate to subclasses the kind of constructor to implement (see How can I force a Constructor to be defined in all subclass of my abstract class)

Now I have an interface that is implemented by many subclasses. The program discovers these sub-classes at runtime through reflection.
I'd like to have a plugin factory that instantiate them (see here for an example).

The problem is that all examples assume that all subclasses have a specific type of constructor (no arguments, for example). But I can't really be sure about this. Since I can't enforce subclasses to have a specific constructor what should I do to avoid runtime errors?

Thank you!

Community
  • 1
  • 1
CarrKnight
  • 2,768
  • 2
  • 23
  • 25

1 Answers1

2

So, since you employ reflection, you can use getConstructor(java.lang.Class...) (sorry, cannot paste a link to the method JavaDoc) to see if the ctor is there, and if it is, call it with specific arguments.

Alexander Pavlov
  • 31,598
  • 5
  • 67
  • 93
  • Yeah, that's what I am doing now. But if such constructor is not specified what do I do but throw an exception? That is, if I expect a no-args constructor and all reflection finds is constructors with arguments I have honestly no idea what the factory should do but crash – CarrKnight May 16 '12 at 17:51
  • Yes, it should crash -- or rather, throw an exception of some kind. These are the tradeoffs of using reflection. – Thorn G May 16 '12 at 18:45