Question regarding access modifiers when used with reflection | Selenium Forum
Y
Yousuf Syed Posted on 20/11/2020

Hi Ashish,

I have a package called "reflections" which contains 2 java files - Operations.java and Client.java.

//Operations.java

package reflections;

public class Operations {

   public void add (int a, int b) {
      int result = a + b;
      System.out.println(result);
   }
   public void diff (int a, int b) {
      int result = a - b;
      System.out.println(result);
   }
   public void mult (int a, int b) {
      int result = a * b;
      System.out.println(result);
  }
 

   //Note the missing keyword "public"

   void div (int a, int b) {
      int result = a / b;
      System.out.println(result);
   }

}

//Client.java

package reflections;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class Client {

      public static void main(String[] args) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
          String operation = "div";
          int x = 10;
          int y = 20;

          Operations op = new Operations(); 
          Method m = op.getClass().getMethod(operation, int.class, int.class);
          m.invoke(op, x, y);
      }

}

 

When i compile Client.java, I get "NoSuchMethodException" error as follows:

Exception in thread "main" java.lang.NoSuchMethodException: reflections.Operations.div(int,int)
at java.base/java.lang.Class.getMethod(Class.java:2109)
at reflections.Client.main(Client.java:18)

When I add the public keyword before the div(), my program compiles and gives the expected result. My question is:

Why am I getting this error even though both the files are in the same package? Default access specifiers are accessible throughout the same package, correct? If you could please help me understand this, I would appreciate your help.

 

 


Y
Yousuf Syed Replied on 30/07/2021

Hi Ashish,

Can you please answer the above question? I am still unable to figure out the answer for this.


A
Ashish Thakur Replied on 04/08/2021

Yes its accessible in same package

But reflections api has got restrictions


Related Posts