Tuesday 13 October 2015

Accessing Private Methods using Java Reflection

Accessing Private Methods

Call Class.getDeclaredMethod(String name, Class[] paramTypes) or Class.getDeclaredMethods() method to obtain the private/public methods.

The methods Class.getMethod(String name, Class[] parameterTypes) and Class.getMethods() methods only return public methods.

package reflection;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
class PrivateObject  {
      private String string;
      public PrivateObject (String string) {
            this.stringstring;
      }

      private String getPrivateMethod() {
            return string;
      }
}

public class TestReflectionMethod {
      public static void main(String[] args) {
          PrivateObject pvtObj = new PrivateObject("Private method");
          try {
              Method privateMethod =
                  PrivateObject.class.getDeclaredMethod
                  ("getPrivateMethod",null);

              /** SecurityException - if the request is denied. */
              privateMethod.setAccessible(true);

              String returnValue =
                           (String) privateMethod.invoke(pvtObj, null);

              System.out.println("using reflection="+returnValue+" accessed!!");

         } catch (IllegalAccessException e) {
         } catch (InvocationTargetException e) {
         } catch (NoSuchMethodException e) {
         }
     }
}

Output: using reflection = Private method accessed!!

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...