Lets say I have classes A
and B
, where B
extends A
. I also have a constructor in B
with one argument which is of type A
. I also have an object of type B
called bObj
.
Is there a way to call B.class.getConstructor(new Class[] { bObj.getClass() })
and get the constructor since B
extends A
? At the moment I'm getting a NoSuchMethodException
.
I suggest you have a look at the ConstructorUtils
from Apache Commons Lang.
They have all manners of constructor discovery methods.
Your case should be covered by "Matching Accessible Constructors".
Here is an example of the method used in context. Basically, you call it like this:
private <T> T instantiate(Class<?> input, Object parameter) {
try {
Constructor<?> constructor = ConstructorUtils.getMatchingAccessibleConstructor(input, parameter.getClass());
return (T) constructor.newInstance(parameter);
} catch (Exception e) {
//handle various exceptions
}
}