Monday, 25 April 2016

How to access private fields of a class ?


Using reflection
Class.getDeclaredMethod(String name, Class[] paramTypes)
Class.getDeclaredMethods() 

Example

MyClass cls = new MyClass();
try {
    Method privateMethod = 
           MyClass.class.getDeclaredMethod("getPrivateMethod"null);
   
    // Throws exception if method can't be accessed 
    privateMethod.setAccessible(true);

    String returnValue = (String) privateMethod.invoke(clsnull);
    System.out.println(returnValue);

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

No comments:

Post a Comment

Note: only a member of this blog may post a comment.