java - 当由 Class 类型变量调用时,getConstructor() 返回 NoSuchMethodException
问题描述
在类型类变量上使用 getConstructor() 时,我不断收到以下异常:java.lang.NoSuchMethodException: Main$Person.()
getConstructors() 和 getDeclaredConstructors() 方法工作正常。我期待代码返回: public Main$Person(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 退出控制台。
解决方案
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).
推荐阅读
- java - Dynamo DB 和 JPA 在 Spring Boot 项目中一起出现错误 Not a managed type: class
- wordpress - 为什么在申请 SSL 证书后安全锁从我的 wordpress 网站上消失了?
- php - 在 Woocommerce 3 上显示默认变化价格和节省金额
- c# - 在不改变实时视频分辨率的情况下同时从 5 个摄像头获取不同分辨率的快照?
- c++ - 检查字体的嵌入类型
- javascript - 为什么这个构造函数不起作用?
- javascript - 无法使用 eq() 获取动态添加的单选按钮子项
- linux - 'cp' 命令后'reboot' 命令不能正常工作
- java - Java在超属性的子构造函数中抛出异常
- sharepoint - 第二个列表中使用的站点列显示行号