Sub topic 2
Class objects: .class, getClass(), and Class.forName()
This chapter assumes you know core Java syntax, packages and imports, and checked exceptions. It covers the entry point to reflection: the Class object.
What a Class object is
Every type the JVM loads has exactly one java.lang.Class object for each class loader that defines it. That object describes the type: its name, superclass, interfaces, fields, methods, and constructors. Reflection always starts here. You get a Class object first, then ask it questions.
Class<T> is generic. String.class has type Class<String>. When you don't know the type at compile time, use Class<?>.
Three ways to get one
| Way | Example | Needs | Failure |
|---|---|---|---|
| Class literal | `String.class` | The type known at compile time | Compile error if the type is missing |
| `getClass()` | `"hello".getClass()` | An object instance | `NullPointerException` on `null` |
| `Class.forName(name)` | `Class.forName("java.lang.String")` | A fully qualified name string | `ClassNotFoundException` (checked) |
The class literal also works for primitives and arrays: int.class, String[].class. getClass() returns the runtime type, so for a variable declared as Object that holds a String, it returns String.class.
Class.forName takes the binary name. For nested classes this means Outer$Inner, not Outer.Inner. It also loads and initializes the class, so static initializers run. This is how a name read from a config file becomes a type.
public class InspectClass {
public static void main(String[] args) throws ClassNotFoundException {
Class<?> a = String.class;
Class<?> b = "hello".getClass();
Class<?> c = Class.forName("java.lang.String");
System.out.println(a == b && b == c);
System.out.println(a.getName());
System.out.println(a.getSuperclass().getName());
for (Class<?> i : a.getInterfaces()) {
System.out.println("implements " + i.getName());
}
}
}The first line prints true. All three expressions return the same object, so you can compare classes with ==. The program then prints java.lang.String and java.lang.Object, followed by one implements line for each interface that String declares directly, such as java.io.Serializable and java.lang.Comparable.
Reading basic information
A few methods you will use constantly:
getName()returns the binary name, such asjava.lang.String.getSimpleName()returns the name without the package, such asString.getSuperclass()returns the parent class, ornullforObject, interfaces, primitives, andvoid.getInterfaces()returns only the interfaces declared directly on that type, not inherited ones.isInterface(),isArray(),isPrimitive(), andisEnum()classify the type.
Common errors
- Passing a simple name such as
"String"toClass.forNamethrowsClassNotFoundException. Use the fully qualified name. - Calling
getClass()on anullreference throwsNullPointerException. A class literal never does. - Class identity depends on the class loader. The same class bytes loaded by two loaders give two different
Classobjects, and==between them isfalse. This matters in application servers and plugin systems.
Exercise
You have Object o = new java.util.ArrayList<String>();. What does o.getClass() == java.util.List.class evaluate to, and why? Which call would correctly test whether o is a List?
Show answer
It evaluates to false. getClass() returns the exact runtime type, ArrayList, and that is a different Class object from List.class. Use List.class.isInstance(o), which returns true for any instance of List or a subtype.