Master Java Reflection: 5 Essential Techniques for Dynamic Code
This article explains Java reflection—a powerful feature used by frameworks like Spring and MyBatis—covering its core concepts and demonstrating five practical ways to invoke methods, access fields, handle static and private methods, and work with superclass methods using concise code examples.
Java reflection is a powerful feature widely used by frameworks such as Spring and MyBatis for dependency injection, dynamic proxies, and other core functionalities.
Reflection enables a program to obtain class information (name, constructors, methods, fields) and to create objects or invoke methods at runtime.
Below are five common reflection operations with complete code examples.
1. Invoke a method without parameters
// Get Class object
Class<?> clazz = Class.forName("com.mikechen.MyClass");
// Invoke no‑arg method
Method method1 = clazz.getDeclaredMethod("testMethod1");
Object result1 = method1.invoke(clazz.newInstance());
System.out.println(result1);2. Invoke a method with parameters
// Get Class object
Class<?> clazz = Class.forName("com.mikechen.MyClass");
// Invoke method with a String argument
Method method2 = clazz.getDeclaredMethod("testMethod2", String.class);
Object result2 = method2.invoke(clazz.newInstance(), "Hello World");
System.out.println(result2);3. Invoke a static method
First obtain the Class object, then retrieve the static method and invoke it with null as the instance.
Class<?> clazz = Class.forName("com.mikechen.MyClass");
Method method = clazz.getMethod("myStaticMethod", String.class, int.class);
Object result = method.invoke(null, "Hello", 123);4. Invoke a private method
Use getDeclaredMethod and setAccessible(true) to bypass access checks.
Method method = clazz.getDeclaredMethod("myPrivateMethod", String.class);
method.setAccessible(true);
method.invoke(obj, "John");5. Invoke a superclass method
Obtain the superclass Class object, then retrieve and invoke the desired method.
Class<?> superClass = clazz.getSuperclass();
Method method = superClass.getDeclaredMethod("parentMethod");
method.invoke(obj);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.
Mike Chen's Internet Architecture
Over ten years of BAT architecture experience, shared generously!
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.
