Java getConstructor()在被类类型变量调用时返回NoSuchMethodException

Java getConstructor()在被类类型变量调用时返回NoSuchMethodException,java,getconstructor,Java,Getconstructor,在对类型类变量使用getConstructor()时,我一直遇到以下异常: java.lang.NoSuchMethodException:Main$Person.() getConstructors()和getDeclaredConstructors()方法工作正常。我希望代码返回:public Main$Person(Main) 什么会导致这种情况?我如何防止它?另外,在所有构造函数中列出的“主要”参数是什么?这是对创建它的实例的引用吗 请参阅下面的代码和输出: 导入java.lang.re

在对类型类变量使用getConstructor()时,我一直遇到以下异常: java.lang.NoSuchMethodException:Main$Person.()

getConstructors()和getDeclaredConstructors()方法工作正常。我希望代码返回:public Main$Person(Main)

什么会导致这种情况?我如何防止它?另外,在所有构造函数中列出的“主要”参数是什么?这是对创建它的实例的引用吗

请参阅下面的代码和输出: 导入java.lang.reflect.*

公共班机{

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());}

 }
public类人事管理器
{
公共事业;
public void supersampleMethod(){}
私有PersonSuper(){System.out.println(“PersonSuper无参数构造函数”);}
}
公共类Person扩展PersonSuper
{
公共信息;
公共void sampleMethod(字符串变量){}
public void sampleMethod2(){}
私人(intageinput){this.age=ageInput;}
公众人物(){}
}
公共静态void main(字符串[]args)引发异常{
try{Class clss=Person.Class;
构造函数c[]=clss.getConstructors();
for(int i=0;i
}

结果: 公共主管道$人(主管道)

公共主设备$人(主设备)
私人主楼$人(主楼,内部)

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

…程序已完成,退出代码为0

按ENTER键退出控制台

当您有一个内部的非静态类时,必须将外部类
Main
指定为
getConstructor()
方法的参数,如文档中所述:

[…]如果此
对象表示在非静态上下文中声明的内部类,则形式参数类型将显式封闭实例作为第一个参数

所以你要么写

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

或者将测试类设置为静态(或者将它们放在单独的文件中)。

这个问题可能与此相关,因为您使用的是嵌套类,如果没有
Main
对象,就无法创建
Person
对象,并且
getConstructor()
知道这一点。您没有提供正确的参数列表。您没有提供任何参数列表。@ChrisC它将是
getConstructor(Main.class,int.class)int
。但是构造函数必须是
public
,如
getConstructor()
方法的文档中所述(或使用
getDeclaredConstructor()
)。