Monday, May 4, 2015

How to access private data members or methods of Class in Java


We know that elementData is private data member of ArraryList class, but here we are getting value of that data member runtime in our program, here we used elementData member variable to see change in capacity of ArrayList, capacity of ArrayList is by default 10, if we will try to store more data than capacity then capacity will increase by 50%.

import java.lang.reflect.Field;
import java.util.ArrayList;

public class PrivateDataMembersValue {

            static Field field;
            public static void main(String[] args) {

                        ArrayList<Integer> arrList =  new ArrayList<Integer>();
                        try {
                                    field = ArrayList.class.getDeclaredField("elementData");
                                    field.setAccessible(true);
                        } catch (NoSuchFieldException e) {
                                    e.printStackTrace();
                        } catch (SecurityException e) {
                                    e.printStackTrace();
                        }
                       
                        for(int i=0; i<=11;i++)
                        {
                                    arrList.add(i);
                        }
                        Object[] elementData;
                       
                       
                        try {
                                    elementData = (Object[]) field.get(arrList);
                                    System.out.println("Actual Size of array list "+arrList.size());
                                    System.out.println("Capacity of elementData---A internal array of ArrayList: " +                                                                          elementData.length );
                        } catch (IllegalArgumentException e) {
                                    e.printStackTrace();
                        } catch (IllegalAccessException e) {
                                    e.printStackTrace();
                        }
                       
                       
            }
}

Output:-
Actual Size of array list 12
Capacity of elementData---A internal array of ArrayList 15


Similarly use private methods using below code

Method m=ArrayList.class.getDeclaredMethod("size");
//m.invoke(d);       //exception java.lang.IllegalAccessException
m.setAccessible(true);

m.invoke(d);          //now its ok

This terminology is called as "Reflection".