Accessing Private Members using Java Reflection PRO

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;
 }
}
 

 

Share:

banner for the css playlist in hebrew life michael courses for programmers

The First Steps in CSS

Learn CSS using our our videos (in Hebrew) on the CSS (he) playlist on youtube. Do it now. Do it for free.

Good Trainers Collaborate with Others

It is always essential to keep an open mind and learn from others. This applies to everyone, including teachers and especially software development trainers. Software

The Beauty of Code

Coding is Art! Developing Code That Works is Simple. Develop Code with Style is a Challenge!

Update cookies preferences