I’m trying to invoke a parameterized constructor of a inherited class with reflection.
But the constructor isn’t implemented in the subclasses, only in the super class.
class Parent{
public Parent(String value){
doSomeThing(value);
}
}
class Horst extends Parent{}
class Eva extends Parent{}
class AndereKlasse{
...
Class parentClass = MyConfig.getParentClass; // its here Horst.class or Eva.class
Constructor parentConstructor = Parent.class.getConstructor(String.class);
parentConstructor.newInstance("just a String");
...
}
I just get the empty constructor from the subclasses but not the one from the Parent-class. Is there a workaround?
This doesn’t work because the subclasses Eva and Horst each have to define their own constructor in order to specify how they call their superclass constructor. Calling the super class’ constructor won’t create an object of the subclass in any case. You need to call a constructor on the subclass in order to create an object of that subclass.