getConstructor() returning NoSuchMethodException when called by a Class type variable

Viewed 191

I keep getting the following exception when using getConstructor() on a type Class variable: java.lang.NoSuchMethodException: Main$Person.()

The getConstructors() and getDeclaredConstructors() methods are working fine. I'm expecting the code to return: public Main$Person(Main)

What would cause this and how can I prevent it? Also, what is the 'Main' parameter listed in all of the constructors? Is this a reference to the instance that created it??

See code and output below:

import java.lang.reflect.*;

public class Main{
    
    public class PersonSuper 
    {
        public int superage; 
        public void supersampleMethod(){} 
        private PersonSuper(){System.out.println("PersonSuper no argument constructor");} 
    }
    public class Person extends PersonSuper
    {
        public int age; 
        public void sampleMethod(String var){} 
        public void sampleMethod2(){}
        private  Person (int ageInput){this.age = ageInput;}
        public  Person(){}
    }

     public static void main(String []args) throws Exception{
         
        try { Class<Person> clss = Person.class;
        
        
            Constructor c[] = clss.getConstructors();
            for (int i = 0; i < c.length; i++)
            {System.out.println(c[i]);}
            Constructor c2[] = clss.getDeclaredConstructors();
            System.out.println();
            for (int i = 0; i < c2.length; i++)
            {System.out.println(c2[i]);}
            System.out.println();
            Constructor con = clss.getConstructor(); //This is the code that is not working...
            System.out.println(con); //This is the code that is not working...
             
        }
        catch(Exception e)
        {System.out.println(e.toString());}
     
     }
}

Results: public Main$Person(Main)

public Main$Person(Main)
private Main$Person(Main,int)

java.lang.NoSuchMethodException: Main$Person.()

...Program finished with exit code 0
Press ENTER to exit console.

1 Answers

You must specify the outer class Main as an argument for the getConstructor() method when you have an inner, non-static class, as mentioned in the getConstructor() documentation:

[...] If this Class object represents an inner class declared in a non-static context, the formal parameter types include the explicit enclosing instance as the first parameter.

So you either write

Constructor con = clss.getConstructor(Main.class);

or make your test classes static (or put them in separated files anyway).

Related