Basic Class Object Methods and Type Information
What You'll Learn
You'll learn how to use simple Class object methods to inspect and ask questions about a type at runtime.
Querying Type Information
Once you have a Class object (via .class or getClass()), you can ask it questions about the type it represents. Think of the Class object as an information booth—you walk up and ask, "What's the name of this type?" or "Is this object an instance of your type?"
Three Essential Methods
getName() returns the fully qualified name of the class (including package):
Class<?> clazz = String.class;
System.out.println(clazz.getName()); // java.lang.String
getSimpleName() returns just the class name without the package:
System.out.println(clazz.getSimpleName()); // String
isInstance(Object obj) checks if an object is an instance of this class (like a runtime instanceof check):
String text = "Hello";
Class<?> stringClass = String.class;
System.out.println(stringClass.isInstance(text)); // true
Integer number = 42;
System.out.println(stringClass.isInstance(number)); // false
Practical Example
public class TypeInspector {
public static void main(String[] args) {
Object obj = "Mystery Object";
Class<?> clazz = obj.getClass();
System.out.println("Full name: " + clazz.getName());
System.out.println("Simple name: " + clazz.getSimpleName());
System.out.println("Is String? " + String.class.isInstance(obj));
System.out.println("Is Integer? " + Integer.class.isInstance(obj));
}
}
Key Takeaway: Use getName() and getSimpleName() to discover type names at runtime, and isInstance() to dynamically check if an object belongs to a specific type—all through the Class object's methods.