【发布时间】:2020-02-09 07:57:57
【问题描述】:
在类型类变量上使用 getConstructor() 时,我不断收到以下异常: java.lang.NoSuchMethodException: Main$Person.()
getConstructors() 和 getDeclaredConstructors() 方法运行良好。我期待代码返回:public Main$Person(Main)
什么会导致这种情况,我该如何预防? 另外,所有构造函数中列出的“Main”参数是什么?这是对创建它的实例的引用吗??
查看下面的代码和输出:
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());}
}
}
结果: 公共 Main$Person(Main)
公共 Main$Person(Main)
私人 Main$Person(Main,int)
java.lang.NoSuchMethodException: Main$Person.()
...程序以退出代码 0 结束
按 ENTER 退出控制台。
【问题讨论】:
-
stackoverflow.com/questions/4070716/instantiating-inner-class 的问题可能是相关的,因为您使用的是嵌套类,并且您无法在没有
Main对象的情况下创建Person对象,而getConstructor()知道这一点。 -
您没有提供正确的参数列表。您没有提供任何参数列表。
标签: java getconstructor