IllegalAccessException
.
setAccessible(true)
method which can be called on Field
,
Method
and Constructor
objects.
setAccessible(true)
import java.lang.reflect.*;
class Demo
{
private String secret = "This is private";
private void showSecret()
{
System.out.println("Secret: " + secret);
}
}
public class MainApp
{
public static void main(String[] args) throws Exception
{
Demo obj = new Demo();
Class<?> c = obj.getClass();
// Try to access private field without setAccessible()
Field f = c.getDeclaredField("secret");
try
{
System.out.println(f.get(obj)); // β Throws IllegalAccessException
}
catch (IllegalAccessException e)
{
System.out.println("Cannot access private field without setAccessible(true)");
}
// Now bypass access control
f.setAccessible(true); // β
Disables access checks
System.out.println("Private Field Value: " + f.get(obj)); // Works fine
}
}
Cannot access private field without setAccessible(true) Private Field Value: This is private
setAccessible(true)
import java.lang.reflect.*;
class Student
{
private String name = "Deepak";
private void showMessage()
{
System.out.println("Hello from private method!");
}
}
public class MainApp
{
public static void main(String[] args) throws Exception
{
Student s = new Student();
Class<?> c = Student.class;
// Access private field
Field field = c.getDeclaredField("name");
field.setAccessible(true); // β
bypass access control
System.out.println("Private Field Value: " + field.get(s));
// Access private method
Method method = c.getDeclaredMethod("showMessage");
method.setAccessible(true); // β
allow invocation
method.invoke(s);
}
}
Private Field Value: Deepak Hello from private method!
Your feedback helps us grow! If there's anything we can fix or improve, please let us know.
Weβre here to make our tutorials better based on your thoughts and suggestions.