Using the Java Reflection API we can access private members from outside the scope of the class they belong to. When the private member is a field we can even change its value and when the private member is a method we can even indirectly invoke it.

The AcceesibleObject class is the base class for Method, Field and Constructor. The AccessibleObject class provides the ability to flag a reflected object and suppress default Java language access control checks. Flagging a reflected object is done by calling the setAccessible method that was defined in the AccessibleObject class. The following code shows that.

package com.abelski.samples;

import java.lang.reflect.*;

public class Demo
{
 public static void main(String[] args) throws
      SecurityException, NoSuchFieldException, NoSuchMethodException, 
      IllegalAccessException, InvocationTargetException, IllegalArgumentException
 {
  Book book = new Book();
  System.out.println(book);
  Class ob = book.getClass();
  Field titleField = ob.getDeclaredField(“title”);
  titleField.setAccessible(true);
  Method multiplePagesMethod = ob.getDeclaredMethod(“multiplePages”,int.class);
  multiplePagesMethod.setAccessible(true);
  titleField.set(book, “GoGoMango”);
  multiplePagesMethod.invoke(book,4);
  System.out.println(book);
 }
}

class Book
{
 private String title = “NoNameTitle”;
 private String author = “NoNameAuthor”;
 private int pages = 100;
 private void multiplePages(int num)
 {
  pages*=num;
 }
 public String toString()
 {
  return title+”:”+author+”:”+pages;
 }
}
 

 

Leave a Reply

Your email address will not be published. Required fields are marked *