Sub topic 1
What Reflection Is and When to Use It
Reflection is Java’s ability to inspect and use classes while a program is running. Instead of referring directly to a class member in source code, reflection lets you discover its name, type, modifiers, and behavior from a Class object.
Reflection is useful for frameworks, dependency injection, serializers, test tools, and plugin systems. It is usually a poor choice for ordinary application logic because it is less type-safe, harder to refactor, and often slower than direct calls.
Prerequisites
Assume you know Java classes, interfaces, constructors, fields, methods, checked exceptions, and basic generics. You should also be able to compile and run a Java 11 program.
Class Objects
A Class<?> object represents a loaded Java type. You can obtain one in several ways:
public class ClassSources {
public static void main(String[] args) throws ClassNotFoundException {
Class<?> a = String.class;
Class<?> b = "hello".getClass();
Class<?> c = Class.forName("java.lang.String");
System.out.println(a == b && b == c);
System.out.println(a.getName());
}
}The .class form is resolved from a type known at compile time. getClass() inspects an existing object. Class.forName() loads a type by its name and therefore reports ClassNotFoundException.
Inspecting and Using Members
A class object provides discovery methods such as getDeclaredFields(), getDeclaredMethods(), and getDeclaredConstructors(). The Declared forms include members declared by that class, including non-public members. Methods such as getMethods() usually expose public members, including inherited ones.
Each member reports details such as its name, type, parameters, and modifiers. Modifiers describe properties such as public, private, static, and final.
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
class Person {
private String name;
public Person(String name) {
this.name = name;
}
}
public class ReflectionBasics {
public static void main(String[] args) throws Exception {
Class<Person> type = Person.class;
for (Constructor<?> c : type.getDeclaredConstructors()) {
System.out.println("constructor: " + c);
}
for (Field f : type.getDeclaredFields()) {
System.out.println(
Modifier.toString(f.getModifiers()) + " " + f.getName()
);
}
Constructor<Person> constructor =
type.getConstructor(String.class);
Person person = constructor.newInstance("Ada");
Field field = type.getDeclaredField("name");
field.setAccessible(true);
System.out.println(field.get(person));
field.set(person, "Grace");
System.out.println(field.get(person));
}
}getConstructor finds a public constructor with the requested parameter types. newInstance creates the object. getDeclaredField finds the field, and get and set read and write its value.
Exercise
Which Class object obtains a type from an existing object?
Show answer
object.getClass() obtains the runtime class of that object.