【问题标题】:Getting nosuchmethod exception获取 nosuchmethod 异常
【发布时间】:2019-05-15 00:06:20
【问题描述】:

这是我的代码

package first_project;
import java.lang.reflect.*; 
import java.util.Scanner;

public class My_Class {

    public static void main(String[] args)throws Exception {
        Scanner sc=new Scanner(System.in);
        //Getting numbers from user
        System.out.println("Enter First Number:");
        int a=sc.nextInt();
        System.out.println("Enter Second Number:");
        int b=sc.nextInt();
        //code for private method
        Class c=addition.class;  
        Method m = addition.class.getDeclaredMethod("add(a,b)");
        m.setAccessible(true);  
        m.invoke(c);
    }
}

package first_project;

//Class for addition
public class addition{
    private void add(int a,int b)
    {
        int ans= a+ b;
        System.out.println("addition:"+ans);
    }
}

这是个例外:

线程“main”中的异常 java.lang.NoSuchMethodException: first_project.addition.add(int a,int b)()
在 java.base/java.lang.Class.getDeclaredMethod(Class.java:2434)
首先_project.My_Class.main(My_Class.java:15)

【问题讨论】:

    标签: java reflection nosuchmethod


    【解决方案1】:

    Method.getDeclaredMethod 接受方法名称和参数类型作为参数。您必须像这样更改它Method m = addition.class.getDeclaredMethod("add", int.class, int.class);

    方法调用也是错误的:

    m.invoke(c); 
    

    应该是:

    m.invoke(*instance of addition*, *first param*, *second param*);
    

    相应地替换*instance of addition*等。

    此外,Java 使用了一些 code conventions,例如:类名必须以大写字母等开头。

    【讨论】:

      【解决方案2】:

      改变这一行:

      addition.class.getDeclaredMethod("add(a,b)");
      

      到这里:

      Method method = addition.class.getDeclaredMethod("add", int.class, int.class);
      

      getDeclaredMethod 将方法名称及其参数类型作为参数。

      调用方法:

      method.invoke(new addition(), a, b);
      

      【讨论】:

      • 此外,当调用m.invoke 时,您应该传递3 个参数:第一个是addition 类的实例,而第二个和第三个参数应该是您的ab
      • 谢谢,错过了。更新了答案。
      • 第一个参数应该是类的instance,而不是类本身。所以使用m.invoke(c.newInstance(), a, b);
      • 另外的小“a”让我认为这是一个实例。感谢您指出。
      • 换行后仍然出现同样的异常。请您在空闲时间检查代码
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-27
      • 1970-01-01
      • 2017-05-20
      • 2012-01-10
      • 2014-10-27
      • 1970-01-01
      相关资源
      最近更新 更多