Java
Summary - Reflection
Combine getMethods and invoke to write an object inspector.
Summary - Reflection
In this group you met the core tools of reflection. Class<?> gives type information; getFields and getMethods list public members; invoke calls methods; getDeclaredConstructors with newInstance produces new instances.
Combining these tools lets frameworks, libraries and test tools inspect and use any class at runtime. For example find the class with Class.forName, get a constructor with getDeclaredConstructor, create an instance with newInstance and call a method with invoke.
Exercise Check whether a method exists
Find the String class with Class.forName("java.lang.String"). Get all methods with getMethods(). Loop through them; if a method named length exists, print true. Add throws ClassNotFoundException to main.
Show example solution
import java.lang.reflect.Method;
public class MethodList {
public static void main(String[] args) throws ClassNotFoundException {
Class<?> c = Class.forName("java.lang.String");
Method[] methods = c.getMethods();
boolean hasLength = false;
for (Method m : methods) {
if (m.getName().equals("length")) {
hasLength = true;
break;
}
}
System.out.println(hasLength);
}
}
When to use reflection
Reflection is used when type information is needed at runtime. Frameworks, libraries and test tools discover classes with it; dependency injection, serialization and annotation processing rely on reflection.
But reflection has a cost: compile-time checks are lost, performance drops, and encapsulation may break. So it should be avoided in ordinary application code and used only when truly needed. As an alternative, interfaces and polymorphism are cleaner in most cases.
Exercise Constructor + newInstance + invoke chain
Define a Book class with a public String title field, a public Book(String title) constructor and a public String describe() method that returns "Book: " + title. Create an instance with getDeclaredConstructor(String.class).newInstance("Java"). Call the method with getMethod("describe").invoke(b) and print the result with System.out.println. Add throws Exception to main.
Show example solution
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
class Book {
public String title;
public Book(String title) {
this.title = title;
}
public String describe() {
return "Book: " + title;
}
}
public class FullReflection {
public static void main(String[] args) throws Exception {
Book b = Book.class.getDeclaredConstructor(String.class).newInstance("Java");
Method m = Book.class.getMethod("describe");
System.out.println(m.invoke(b));
}
}
Test yourself
-
Which method calls a Method object at runtime?
- newInstance
- invoke
- getMethod
- forName
Show answer
invoke — invoke calls a Method object.
-
Match each method with its behavior
- Class.forName
- Find a class by name
- getMethods
- List methods
- invoke
- Call a method
- newInstance
- Create an instance
Next lesson: Built-in annotations