Search⌘ K
AI Features

Solution: The Method Counter

Explore how to use Java reflection to count and separate public methods declared in a class. Understand the distinction between inherited Object methods and specific business methods by inspecting method declarations. This lesson helps you grasp runtime code inspection and method categorization in Java applications.

We'll cover the following...
Java 25
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
public class MethodCounter {
public static void analyzeClass(Class<?> clazz) {
List<String> businessMethods = new ArrayList<>();
List<String> objectMethods = new ArrayList<>();
Method[] methods = clazz.getMethods();
for (Method method : methods) {
if (method.getDeclaringClass() == Object.class) {
objectMethods.add(method.getName());
} else {
businessMethods.add(method.getName());
}
}
System.out.println("Analysis of " + clazz.getSimpleName() + ":");
System.out.println("Business Methods (" + businessMethods.size() + "): " + businessMethods);
System.out.println("Standard Methods (" + objectMethods.size() + "): " + objectMethods);
}
public static void main(String[] args) {
analyzeClass(PaymentProcessor.class);
}
}
...