0

i am new to programming and 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)

dquijada
  • 1,544
  • 3
  • 13
  • 21

2 Answers2

3

The Method.getDeclaredMethod accepts as arguments the method name and the parameter types. You have to change it like this Method m = addition.class.getDeclaredMethod("add", int.class, int.class);

The method invocation is also wrong:

m.invoke(c); 

should be:

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

Replace *instance of addition* etc. accordingly.

Also, Java uses some code conventions like: the class name must start with a capital letter etc.

2

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