Java – use reflection to access constructors from abstract base classes
I'm playing java reflection I have an abstract class base with a constructor
abstract class Base { public Base( String foo ) { // do some magic } }
I also have some classes that extend base They don't have much logic I want to instantiate them with the base constructor instead of writing some proxy constructors in these derived classes Of course, I want to instantiate those derived classes with reflection Say:
Class cls = SomeDerivedClass.class; Constructor constr; constr = cls.getConstructor( new Class[] { String.class } ); // will return null Class clsBase = Base.class; constr = clsBase.getConstructor( new Class[] { String.class } ); // ok Base obj = (Base) constr.newInstance( new Object[] { "foo" } ); // will throw InstantiationException because it belongs to an abstract class
Any idea, how can I instantiate a derived class with the constructor of base? Or do I have to declare those stupid proxy constructors?
Solution
Class does not inherit constructors from its parent Class has no parent constructor (although it can call them), so you must call the constructor that the class has, not the constructor that the superclass has
The default constructor seems to do just that because it calls the default constructor of the parent by default If the parent does not have a default constructor, its immediate children cannot