首页 > 解决方案 > 当由 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 退出控制台。

标签: javagetconstructor

解决方案


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).


推荐阅读