Access private field/member java using reflection - Java @ Desk

Saturday, June 29, 2013

Access private field/member java using reflection

We all know, in java we cannot access private members of a class outside that class. Private members are accessible only within the class.
In order to access private field/method or member outside the class, we need to use reflection in java.
Through reflection, private members are accessible outside the class also.

Before Reflection
After Reflection

As you can see clearly, before reflection only public member were visible.  But after reflection all the fields are visible.

Consider the below code,
 package test;  
 public class ReflectionPojo {  
      private String name;  
      private int age;  
 }  
 package test;  
 import java.lang.reflect.Field;  
 import java.lang.reflect.Modifier;  
 public class AccessPrivateMembersMain {  
      public static void main(String args[]) throws NoSuchFieldException,  
                SecurityException, IllegalArgumentException, IllegalAccessException {  
           ReflectionPojo reflectionPojo = new ReflectionPojo();  
           Field f = reflectionPojo.getClass().getDeclaredField("lastName");  
           f.setAccessible(true);  
           f.set(reflectionPojo, "Kumar");  
           System.out.println(f.get(reflectionPojo));  
      }  
 }  
As shown above, we have ReflectionPojo class and it has 2 private fields, name and age.

In order to use the fields in AccessPrivateMembersMain, we have to use reflection.
getDeclaredField() method throws 2 exceptions NoSuchFieldException, SecurityException and it is self-explanatory, like for example we pass a string to this method which is a field name of the class and if there is no field with that name in the class, it will throw NoSuchFieldException

It throws IllegalArgumentException, because if we set a int value in a string field then that will go wrong.







No comments:

Post a Comment