Reflection and Polymorphism in Java: Concepts, Implementation, and Practical Applications
This article explains Java's reflection and polymorphism mechanisms, detailing their theoretical foundations, runtime type identification (RTTI), method table implementation, practical code examples, common use cases, performance and security drawbacks, and the differences between reflection and polymorphism.
In Java, reflection and polymorphism are two distinct runtime techniques that enable programs to discover and manipulate type information; reflection provides full access to a class's fields, methods, and constructors, while polymorphism allows a single reference to invoke different implementations based on the actual object type.
Polymorphism
Polymorphism in Java refers to runtime (dynamic) polymorphism, where a superclass reference can point to subclass objects, requiring inheritance, method overriding, and the parent reference pointing to a child instance. It is implemented via method tables (v‑tables) that store pointers to concrete method implementations, allowing the JVM to resolve the correct method at runtime.
Typical usage includes declaring variables as List list = new ArrayList(); or method parameters as public void test(List list) , enabling flexible substitution of implementations such as ArrayList with LinkedList without changing client code.
Run‑Time Type Identification (RTTI)
RTTI (Run‑Time Type Identification) is the foundation of polymorphism; it lets the JVM determine the actual class of an object when only a superclass reference is available. The JVM obtains a Class object for each loaded class, which can be retrieved via obj.getClass() or Class.forName("full.ClassName") .
Reflection
Reflection allows a program to inspect and manipulate classes at runtime, providing access to all members—including private ones—through the java.lang.Class and java.lang.reflect APIs. Core methods include Class.getFields() , Class.getMethods() , and Class.getConstructors() , which return Field , Method , and Constructor objects respectively.
Typical reflection workflow:
Obtain a Class object: Class clazz = Class.forName("com.example.MyClass");
Retrieve members: Method[] methods = clazz.getDeclaredMethods();
Make private members accessible: method.setAccessible(true);
Invoke methods or access fields: method.invoke(instance, args);
Implementation Details
The JVM creates a Class object for every loaded class via the class loader's defineClass method. Method tables store pointers to each class's methods; for overridden methods, the subclass entry shares the same slot, enabling dynamic dispatch. Interface method calls use the invokeinterface instruction, which requires a lookup rather than a fixed offset, making them slightly slower than class method calls ( invokevirtual ).
Applications
Frameworks such as Spring and MyBatis rely heavily on reflection for bean creation and dependency injection.
JDBC drivers use reflection to load database drivers.
Dynamic proxies and annotation processing.
Factory patterns and code generation tools.
Drawbacks
Performance overhead due to lack of compile‑time optimizations.
Security restrictions in sandboxed environments.
Potential to break encapsulation and cause maintenance issues.
Loss of compile‑time type checking, leading to runtime failures.
Key Reflection Classes
Class : Represents a loaded class and provides methods to obtain Field , Method , and Constructor objects.
Field : Represents a class's member variable; can be read or modified via get and set .
Method : Represents a class's method; can be invoked with invoke .
Reflection Example
Model class:
package com.dr.Reflection.getMethodByReflect;
public class Student {
// public method
public void show1(String s) {
System.out.println("调用了:公有的,String参数的show1(): s = " + s);
}
// protected method
protected void show2() {
System.out.println("调用了:受保护的,无参的show2()");
}
// default (package‑private) method
void show3() {
System.out.println("调用了:默认的,无参的show3()");
}
// private method with return value
private String show4(int age) {
System.out.println("调用了,私有的,并且有返回值的,int参数的show4(): age = " + age);
return "abcd";
}
}Test class demonstrating reflection:
package com.dr.Reflection.getMethodByReflect;
import java.lang.reflect.Method;
public class MethodClass {
public static void main(String[] args) throws Exception {
// 1. Obtain Class object
Class stuClass = Class.forName("com.dr.Reflection.getMethodByReflect.Student");
// 2. List all public methods (including inherited from Object)
System.out.println("***************获取所有的”公有“方法*******************");
for (Method m : stuClass.getMethods()) {
System.out.println(m);
}
// 3. List all declared methods (including private, excluding inherited)
System.out.println("***************获取所有的方法,包括私有的*******************");
for (Method m : stuClass.getDeclaredMethods()) {
System.out.println(m);
}
// 4. Access a specific public method
Method m = stuClass.getMethod("show1", String.class);
System.out.println(m);
Object obj = stuClass.getConstructor().newInstance();
m.invoke(obj, "刘德华");
// 5. Access a private method
System.out.println("***************获取私有的show4()方法******************");
m = stuClass.getDeclaredMethod("show4", int.class);
System.out.println(m);
m.setAccessible(true);
Object result = m.invoke(obj, 20);
System.out.println("返回值:" + result);
}
}Common Questions
Why can private methods be accessed via reflection? Private is meant for encapsulation, not security; reflection bypasses access checks, which is useful for tools but should be used cautiously.
Difference Between Reflection and Polymorphism
Both retrieve information at runtime, but polymorphism determines which implementation to invoke, while reflection discovers the full class structure.
Polymorphism is a language feature; reflection is a Java API for dynamic introspection.
Top Architect
Top Architect focuses on sharing practical architecture knowledge, covering enterprise, system, website, large‑scale distributed, and high‑availability architectures, plus architecture adjustments using internet technologies. We welcome idea‑driven, sharing‑oriented architects to exchange and learn together.
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.