Java Reflection getConstructor Method

Suppose I have classes A and B , where B extends A I also have a constructor in B with one argument that 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 am getting a NoSuchMethodException .

Regards, Stan

+7
source share
3 answers

I suggest you take a look at ConstructorUtils from Apache Commons Lang .
They have all the ways to detect a constructor.

Your case should be covered by " Matching Available 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 } } 
+6
source

No, methods that look for the expected exact parameters for you. Therefore, when you search for a constructor, method, or field using the lookup / search methods of the reflection API, the API uses equals() to find matches.

If you need the same logic as the Java compiler, you will need to use a framework like FEST Reflect or commons beanutils . Or you should call getConstructors() and write your own filter code.

At first glance, this seems silly: if the Java compiler can do it, why not use the Reflection API? There are two reasons: first, for the Java runtime, there is no need to look for which method to call, because the compiler has already selected the correct method.

The second reason is that the Reflection API has always been "second best." He can do everything except his goal has never been so easy / convenient to use (at least what I think every time I use it :-)

+3
source

if your constructor is not public (or if it is not public) or inaccessible from your code area, it will not be returned via

 Class.getConstructor() 

to try

 Class.getDeclaredConstructor() 

instead

0
source

All Articles