1

This program ran fine when test() method was public but as soon as I changed its modifier to private it showed Run time error.Can anybody explain why?

 package ObjectClass;
 import java.lang.reflect.Method;

 public class reflect8 {

      public static void main(String[] args) throws Exception {

           Class c1 = Class.forName("ObjectClass.Reflect8A");

           Object obj = c1.newInstance();

           Method m1 = c1.getDeclaredMethod("test");

           m1.invoke(obj);

   }
}

class Reflect8A {

       private void test() {

           System.out.println("from test...");
       }
   }
Aamir
  • 2,380
  • 3
  • 24
  • 54

2 Answers2

3
 Method m1 = c1.getDeclaredMethod("test");
 m1.setAccessible(true);
 m1.invoke(obj);
Tkachuk_Evgen
  • 1,334
  • 11
  • 17
  • @Tkachur_evgen,it worked but since we r getting an instance of a class at runtime, why can't we access private methods through that instance without calling setAccessible(true) – Aamir Dec 03 '14 at 11:35
  • @Aamir, because private modifier specifies that member can only be accessed within its own class – Tkachuk_Evgen Dec 03 '14 at 11:40
3

Here is why you need to call setAccessible(true) even if getDeclaredMethod returns the private method.

Javadoc of getDeclaredMethod (emphasis mine):

Returns an array containing Method objects reflecting all the declared methods of the class or interface represented by this Class object, including public, protected, default (package) access, and private methods, but excluding inherited methods.

Javadoc of invoke:

Throws IllegalAccessException - if this Method object is enforcing Java language access control and the underlying method is inaccessible.

Javadoc of setAccessible (emphasis mine):

Set the accessible flag for this object to the indicated boolean value. A value of true indicates that the reflected object should suppress Java language access checking when it is used.

assylias
  • 321,522
  • 82
  • 660
  • 783