Mastering Java Reflection: Key Techniques, Pitfalls, and Performance Tips
This article explains Java's reflection mechanism, compares .class and Class.forName, clarifies instanceof and getClass behavior, outlines getDeclaredXXX methods, shows how to invoke methods, constructors, and fields via reflection, and provides practical tips to improve reflection performance and thread safety.
What is Java Reflection?
Java reflection allows a program, at runtime, to discover a class's fields, methods, constructors, and other metadata, and to invoke them dynamically on any object.
How Reflection Maps Class Components
Each component of a class—such as member variables, methods, constructors, and packages—is represented as a distinct Java object, enabling inspection and manipulation.
Common Questions and Answers
Q: Difference between ClassName.class and Class.forName("ClassName") ? A: .class does not trigger static initialization, while Class.forName does.
Q: Can instanceof compare a subclass with its parent class? A: Yes, it returns true.
Q: Can obj.getClass() == Parent.class compare with the parent class? A: No, this causes a compile‑time error because getClass() returns ? extends Subclass, not Parent.class.
Q: Does obj.getClass().equals(Parent.class) return true ? A: It compiles but returns false.
Q: What are the five getDeclaredXXX variants? A: Annotation, Inner Class, Constructor, Field, Method.
Q: What does getMethods() return versus getDeclaredMethods() ? A: getMethods() returns all public methods from the class, its superclasses, and interfaces; getDeclaredMethods() returns all methods declared in the class itself.
Using Reflected Objects
Invoke a method: method.invoke(object, args) Instantiate via constructor: constructor.newInstance(args) Access a field: field.get(object) and field.set(object, value) Q: What does method.getModifiers() return? A: An integer representing the method's modifiers (public, static, etc.).
Common Pitfall Example
package com.huawei.test;
public class A {
public A(int i) {
System.out.printf("i=" + i);
}
public static void main(String[] args) {
try {
A a = (A) Class.forName("com.huawei.test.A").newInstance();
} catch (Exception e) {
e.printStackTrace();
}
}
}A InstantiationException occurs because class A lacks a no‑arg constructor. Fix by obtaining the appropriate constructor:
A a = (A) Class.forName("A").getConstructor(int.class).newInstance(123);Improving Reflection Performance
Use high‑performance libraries such as ReflectASM.
Cache reflective objects to avoid repeated lookups.
Disable security checks with method.setAccessible(true).
Prefer Class.getMethod(name, …) over Class.getMethods() when possible.
Leverage JVM JIT optimizations for reflection.
Thread Safety
Reflection is thread‑safe; internal data is obtained using CAS operations.
Performance Differences
Normal method calls are faster because they can be inlined and optimized by the JIT. Reflection incurs overhead from parameter boxing/unboxing, visibility checks, and inability to inline. Disabling security checks reduces some of this overhead.
Method Caching Details
JVM caches reflective data internally, but each Method object returned to user code is a copy. The cache is held via a soft reference and may be reclaimed under memory pressure.
private Class.ReflectionData<T> reflectionData() {
SoftReference<Class.ReflectionData<T>> reflectionData = this.reflectionData;
int classRedefinedCount = this.classRedefinedCount;
Class.ReflectionData rd;
return reflectionData != null && (rd = (Class.ReflectionData) reflectionData.get()) != null
&& rd.redefinedCount == classRedefinedCount ? rd : this.newReflectionData(reflectionData, classRedefinedCount);
}References
https://segmentfault.com/q/1010000003004720
https://www.cnblogs.com/coding-night/p/10772631.html
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.
Huawei Cloud Developer Alliance
The Huawei Cloud Developer Alliance creates a tech sharing platform for developers and partners, gathering Huawei Cloud product knowledge, event updates, expert talks, and more. Together we continuously innovate to build the cloud foundation of an intelligent world.
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.
