获取 nosuchmethod 异常
Getting nosuchmethod exception
这是我的代码
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 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)
更改此行:
addition.class.getDeclaredMethod("add(a,b)");
对此:
Method method = addition.class.getDeclaredMethod("add", int.class, int.class);
getDeclaredMethod
将方法名称及其参数类型作为参数。
调用方法:
method.invoke(new addition(), a, b);
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,例如:class 名称必须以大写字母开头等。
这是我的代码
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 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)
更改此行:
addition.class.getDeclaredMethod("add(a,b)");
对此:
Method method = addition.class.getDeclaredMethod("add", int.class, int.class);
getDeclaredMethod
将方法名称及其参数类型作为参数。
调用方法:
method.invoke(new addition(), a, b);
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,例如:class 名称必须以大写字母开头等。