首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >获取nosuchmethod异常

获取nosuchmethod异常
EN

Stack Overflow用户
提问于 2018-12-13 17:50:10
回答 2查看 263关注 0票数 0

这是我的密码

代码语言:javascript
复制
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,int )() 在java.base/java.lang.Class.getDeclaredMethod(Class.java:2434) 在first_project.My_Class.main(My_Class.java:15)

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-12-13 17:54:50

更改这一行:

代码语言:javascript
复制
addition.class.getDeclaredMethod("add(a,b)");

对此:

代码语言:javascript
复制
Method method = addition.class.getDeclaredMethod("add", int.class, int.class);

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

要调用该方法:

代码语言:javascript
复制
method.invoke(new addition(), a, b);
票数 2
EN

Stack Overflow用户

发布于 2018-12-13 17:55:20

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

方法调用也是错误的:

代码语言:javascript
复制
m.invoke(c); 

应:

代码语言:javascript
复制
m.invoke(*instance of addition*, *first param*, *second param*);

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

另外,Java使用了一些代码约定,比如:类名必须以大写字母等开头。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53767524

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档