Invoking Private Methods in Java using Reflection PRO

Using the Java Reflection API we can indirectly invoke private methods from outside the scope of the class they belong to. 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. Calling the setAccessible method that was defined in the AccessibleObject class passing over the false boolean value we can indirectly invoke a private method from outside the scope of its class. The following code sample shows that.

import java.lang.reflect.Method;

public class Dmo
{
public static void main(String[] args) throws Exception
{
Person per = new Person();
//per.setName(“david”);
Method meth = Person.class.getDeclaredMethod(“setName”,String.class);
meth.setAccessible(true);
meth.invoke(per, “david”);
System.out.println(per);
}
}

class Person
{
private String name;
private void setName(String str)
{
name = str;
}
public String toString()
{
return name;
}
}

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