Inspecting Classes and Methods with Reflection

On Day 4, "Working with Objects," you learned how to create Class objects that represent the class to which an object belongs. Every object in Java inherits the getClass() method, which identifies the class or interface of that object. The following statement creates a Class object named keyclass from an object referred to by the variable key:

Class keyClass = key.getClass();

By calling the getName() method of a Class object, you can find out the name of the class:

String keyName = keyClass.getName();

These features are part of Java's support for reflection, a technique that enables one Java class—such as a program you write—to learn details about any other class.

Through reflection, a Java program ...

Get Sams Teach Yourself Java 2 in 21 Days, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.