【问题标题】:getConstructor() returning NoSuchMethodException when called by a Class type variable当由 Class 类型变量调用时,getConstructor() 返回 NoSuchMethodException
【发布时间】: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


【解决方案1】:

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

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

所以你要么写

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

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

【讨论】:

  • @ChrisC 它应该是getConstructor(Main.class, int.class);,因为参数的类型是int。但构造函数必须是public,如getConstructor() 方法的文档中所述(或使用getDeclaredConstructor())。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-29
  • 1970-01-01
  • 1970-01-01
  • 2015-12-08
  • 1970-01-01
相关资源
最近更新 更多