Using Java Reflection to Access Private Fields and Methods
This article explains how Java reflection can be used to bypass private access modifiers, demonstrating code examples to access private fields, constructors, and methods, and discusses the advantages and disadvantages of using reflection in backend development.
In Java, private fields and methods are normally inaccessible from outside the class, but the reflection API allows developers to bypass this restriction.
The article first defines a Reflect class with private fields name and age, a private constructor, a private method speak, and a public constructor.
/**
* @Description: 反射
* @author: Mr_VanGogh
*/
public class Reflect {
private String name;
private int age;
private Reflect(int age) {
this.age = age;
}
private void speak(String name) {
System.out.println("My name is" + name);
}
public Reflect(String name) {
this.name = name;
}
}It then explains the key reflection classes: Constructor, Method, Field, and their common superclass AccessibleObject, which provides the setAccessible(true) method to suppress Java's access checks.
The main method demonstrates how to obtain Method and Field objects from the Reflect class, set them accessible, and invoke or read their values, effectively retrieving private data.
public static void main(String[] args) throws Exception {
Reflect reflect = new Reflect("a");
Method[] methods = Reflect.class.getMethods();
Field[] fields = Reflect.class.getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
fields[i].setAccessible(true);
System.out.println(fields[i].getName());
}
for (int j = 0; j < methods.length; j++) {
methods[j].setAccessible(true);
System.out.println(methods[j].getName());
methods[j].invoke(reflect);
System.out.println(methods[j].getName());
}
}Finally, the article lists the pros of reflection—runtime flexibility and powerful dynamic capabilities—and the cons—performance overhead, security risks, and violation of encapsulation.
It concludes with a Q&A explaining that the private modifier is intended as a design guideline rather than an absolute security barrier.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Selected Java Interview Questions
A professional Java tech channel sharing common knowledge to help developers fill gaps. Follow us!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
