Monday, 25 April 2016

How to access private members of a class ?


Access private methods using reflection
Class.getDeclaredMethod(String name, Class[] paramTypes)
Class.getDeclaredMethods() 

Example
class MyClass  {
      private String getPrivateMethod() {
            return "hello, I am private";
      }
}

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) { }




Access private fields using reflection
Class.getDeclaredFields() 
Class.getFields()
Class.getFields(String name)

Example
class MyClass  {
      private String pr1;
      private String pr2;
      public  String pb1;
}


// To access private and public fields
Field[] allFields MyClass.class.getDeclaredFields();
for (Field field : allFields) {
   if (Modifier.isPrivate(field.getModifiers())) {
         System.out.println("PRIVATE : " + field.getName());
   }

}

// To access only public fields
Field[] fields = MyClass.class.getFields();

for(Field field : fields) {
   System.out.println(field.getName());
}

No comments:

Post a Comment

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