Showing posts with label CoreJava. Show all posts
Showing posts with label CoreJava. Show all posts

Wednesday, November 16, 2011

Accessing Private Methods and Variables in Java

 It is possible to accessing private data members of a java class,from any other classes.
You can achieve this by using reflection API

*****************************AccessingPrivateVariable.java*****************************

import java.lang.reflect.Field;
 import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
class BaseClass 
    private String msg= "HelloWorld";
    private String getMsg()
    {
      return msg;
    }
   }
public class AccessingPrivateVariable
{
  public static void main(String[] args)throws IllegalAccessException, InvocationTargetException
  {
     BaseClass bc = new BaseClass();
     Class cls = bc.getClass();
      System.out.println("********Accessing all the methods*************"); 
      Method methods[] = cls.getDeclaredMethods(); 
      for (int i = 0; i < methods.length; i++) 
      { 
           System.out.println(methods[i].getReturnType()+" " +methods[i].getName());
           methods[i].setAccessible(true);
           System.out.println(methods[i].invoke(bc) );
       }
    //  Print all the field names & values
    System.out.println("**************Accessing all the fields************");
    Field fields[] = cls.getDeclaredFields();
    for (int i = 0; i < fields.length; i++){ 
       System.out.println("Field Name: " + fields[i].getName()); 
       fields[i].setAccessible(true); 
       System.out.println(fields[i].get(bc)); 
   }
 }
}

*****************************************PROGRAM ENDS**************************