Search code examples
javareflectionnosuchmethod

Getting nosuchmethod exception


Here is my code

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

This is 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)


Solution

  • Change this line :

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

    to this:

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

    getDeclaredMethod takes method name and its parameters type as argument.

    To invoke the method:

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