Invoking Constructor using reflection produces NoSuchMethodException

Go To StackoverFlow.com

1

Given class Award :

public class Award {


    /*
     * 
     */

    // fields of the class 

    Award()
    {
        // some initializations


    }

I'm trying to invoke this constructor from Main :

    try
    {
        Award myAward = Award.class.getConstructor().newInstance();
        myAward.calculateAward(); 
    }

    catch (Exception e) 
    {
       e.printStackTrace();
    }

but it goes into the exception block and produces NoSuchMethodException exception .

What's wrong ?

Thanks !

2012-05-08 05:32
by ron
can you create an instance of a method - Satya 2012-05-08 05:33
@Satya: If I do this "Award a = new Award();" then the code works - ron 2012-05-08 05:39
the line Award a = new Award(); is creating an object of the class Award - Satya 2012-05-08 05:41


9

The issue is your constructor is not public so you will need to use getDeclaredConstructor().newInstance(); or make the constructor public.

2012-05-08 05:37
by Krrose27
Got it , thank you - ron 2012-05-08 05:41
@ron no problem - Krrose27 2012-05-08 05:41
or just use dp4j's '@Reflect' annotation (and it will generate Krroae's code for you) or make it public (if you can) and document that with Google's '@PublicForTesting' annotation - simpatico 2012-05-12 11:31


2

According to the Javadoc:

The constructor to reflect is the public constructor of the class represented by this Class object whose formal parameter types match those specified by parameterTypes.

You constructor may need to be public. Add the public keyword before your Award constructor and try again.

2012-05-08 05:37
by Alexis King
Ads