gpt4 book ai didi

java - 获取 nosuchmethod 异常

转载 作者:行者123 更新时间:2023-12-01 16:44:51 25 4
gpt4 key购买 nike

这是我的代码

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);
}
}

这是异常(exception):

Exception in thread "main" java.lang.NoSuchMethodException: first_project.addition.add(int a,int b)()
at java.base/java.lang.Class.getDeclaredMethod(Class.java:2434)
at first_project.My_Class.main(My_Class.java:15)

最佳答案

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

方法调用也是错误的:

m.invoke(c); 

应该是:

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

相应地替换*添加实例*等。

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

关于java - 获取 nosuchmethod 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53767524/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com