Mastering Java Reflection: Inspecting Classes, Methods, and Fields at Runtime
Mastering Java Reflection
Learn how Java’s reflection API lets you inspect and modify classes, methods, fields, and constructors during runtime, enhancing flexibility and enabling powerful dynamic behaviors.
In Java, reflection enables you to examine and manipulate classes, interfaces, constructors, methods, and fields while the program is running.
Java provides the Class class, which encapsulates metadata about a class or interface. An instance of Class is the gateway to the reflection capabilities.
Obtaining a Class Object
To perform reflection you first need a Class object. There are three common ways to obtain it:
- Using
Class.forName()Class<Dog> clazz = Class.forName("com.example.Dog");The method accepts the fully qualified class name and loads the class if it isn’t already.
- Using
getClass()on an instanceDog dog = new Dog(); Class<Dog> clazz = dog.getClass();Retrieves the runtime class of the object.
- Using the
.classliteralClass<Dog> clazz = Dog.class;Provides a compile‑time reference to the
Classobject.
Once you have a Class instance, you can query its methods, fields, constructors, and annotations.
Practical Example: Inspecting the Dog Class
import java.lang.Class;
import java.lang.reflect.*;
class Animal {}
public class Dog extends Animal {
public void display() {
System.out.println("I am a dog.");
}
}
public class Main {
public static void main(String[] args) {
try {
Dog dog = new Dog();
Class<Dog> clazz = dog.getClass();
System.out.println("Name: " + clazz.getName());
System.out.println("Modifier: " + Modifier.toString(clazz.getModifiers()));
System.out.println("Superclass: " + clazz.getSuperclass().getName());
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output
Name: com.example.Dog Modifier: public Superclass: com.example.Animal
In this snippet, we created a Dog instance, obtained its Class object, and queried the class name, access modifier, and superclass.
For deeper insight into Class, consult the official Java Class documentation.
Exploring Fields, Methods, and Constructors
The java.lang.reflect package offers dedicated classes to introspect specific members:
Method– details about methods.Field– details about fields.Constructor– details about constructors.
Reflecting Methods
The Method class exposes metadata such as name, return type, and modifiers. Below is a concise example:
import java.lang.reflect.*;
class Dog {
public void display() { System.out.println("I am a dog."); }
private void makeSound() { System.out.println("Bark Bark"); }
}
public class Main {
public static void main(String[] args) {
try {
Dog dog = new Dog();
Method[] methods = dog.getClass().getDeclaredMethods();
for (Method m : methods) {
System.out.println("Method Name: " + m.getName());
System.out.println("Modifier: " + Modifier.toString(m.getModifiers()));
System.out.println("Return Type: " + m.getReturnType());
System.out.println();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output
Method Name: display Modifier: public Return Type: void Method Name: makeSound Modifier: private Return Type: void
For a comprehensive list of Method utilities, visit the official Method documentation.
Reflecting Fields
Fields can be accessed and modified at runtime. The Field class provides get, set, and modifier utilities. Example:
import java.lang.reflect.*;
class Dog {
public String type;
private String color;
}
public class Main {
public static void main(String[] args) {
try {
Dog dog = new Dog();
Class<Dog> clazz = dog.getClass();
// Public field
Field typeField = clazz.getField("type");
typeField.set(dog, "labrador");
System.out.println("Value: " + typeField.get(dog));
System.out.println("Modifier: " + Modifier.toString(typeField.getModifiers()));
// Private field
Field colorField = clazz.getDeclaredField("color");
colorField.setAccessible(true);
colorField.set(dog, "brown");
System.out.println("Value: " + colorField.get(dog));
System.out.println("Modifier: " + Modifier.toString(colorField.getModifiers()));
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output
Value: labrador Modifier: public Value: brown Modifier: private
Explore the Field class documentation for advanced usage.
Reflecting Constructors
Constructors are introspected via the Constructor class. The following code lists all constructors of Dog:
import java.lang.reflect.*;
class Dog {
public Dog() {}
private Dog(int age) {}
}
public class Main {
public static void main(String[] args) {
try {
Constructor<Dog>[] cons = Dog.class.getDeclaredConstructors();
for (Constructor<Dog> c : cons) {
System.out.println("Constructor Name: " + c.getName());
System.out.println("Modifier: " + Modifier.toString(c.getModifiers()));
System.out.println("Parameters: " + c.getParameterCount());
System.out.println();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output
Constructor Name: Dog Modifier: public Parameters: 0 Constructor Name: Dog Modifier: private Parameters: 1
For further details, see the Constructor documentation.
Java
- Understanding Java’s final Keyword: Variables, Methods, and Classes
- Mastering Java Inheritance: Concepts, Types, and Practical Examples
- Mastering Java Anonymous Inner Classes: Definition, Syntax, and Practical Examples
- Mastering Java’s ObjectInputStream: A Comprehensive Guide
- Mastering Java ObjectOutputStream: Serialization, Methods, and Practical Examples
- Mastering Java’s PrintStream Class: Print, Println, and Printf Explained
- Mastering Java Reader Class: Subclasses, Methods, and Practical Example
- Mastering Java Generics – Building Reusable, Type‑Safe Code
- Mastering Java File Operations with java.io – Creation, Reading, Writing & Deletion
- Master Java Reflection API: A Practical Guide with Code Examples