Inspecting Superclass and Interfaces
You'll learn how to navigate Java's inheritance hierarchy using reflection to discover a class's parent and implemented interfaces.
In Java, every class (except Object) inherits from exactly one superclass, and may implement multiple interfaces. The Reflection API lets you inspect this type hierarchy at runtime, revealing the inheritance structure that defines a class's capabilities and relationships.
Navigating Up the Class Hierarchy
Use getSuperclass() to retrieve the immediate parent class:
Class<?> stringClass = String.class;
Class<?> parent = stringClass.getSuperclass();
System.out.println(parent.getName()); // java.lang.Object
If a class has no superclass (only Object itself), this returns null.
Discovering Implemented Interfaces
Use getInterfaces() to get an array of directly implemented or extended interfaces:
Class<?> arrayListClass = ArrayList.class;
Class<?>[] interfaces = arrayListClass.getInterfaces();
for (Class<?> intf : interfaces) {
System.out.println(intf.getName());
}
// Output: java.util.List, java.util.RandomAccess,
// java.lang.Cloneable, java.io.Serializable
Important: getInterfaces() returns only the direct interfaces, not those inherited from superclasses.
Traversing the Full Hierarchy
You can walk up the entire inheritance chain by repeatedly calling getSuperclass():
Class<?> current = ArrayList.class;
while (current != null) {
System.out.println(current.getName());
current = current.getSuperclass();
}
// Output: ArrayList → AbstractList → AbstractCollection → Object
Key Takeaway: Use getSuperclass() to climb the inheritance tree and getInterfaces() to discover direct interface implementations, enabling complete runtime inspection of a class's type relationships.