Sub topic 2
Class objects: .class, getClass(), and Class.forName()
Every reflection operation starts from a java.lang.Class object. This chapter covers what that object is, three ways to get one, how the three differ, and what you can read from it right away. It assumes you know core Java syntax, basic generics, checked exceptions, and how to compile and run a program from the command line.
What a Class object is
When the JVM loads a type, it creates one Class instance that describes that type. The type can be a class, an interface, an enum, an annotation, an array, or a primitive. The Class object holds the type's name, its superclass, its interfaces, its modifiers, and its members. Later chapters use it to reach fields, methods, and constructors.
Two facts are worth fixing in your mind:
- A
Classobject is not an instance of the type it describes.String.classis an object of typeClass<String>, not a string. - Within one class loader, a type has exactly one
Classobject. That is why==is the correct way to compare them.
Three ways to get a Class object
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());
}
}
}On Java 11 this prints true, java.lang.String, java.lang.Object, and then one line each for java.io.Serializable, java.lang.Comparable, and java.lang.CharSequence. Newer Java versions list additional interfaces.
The comparison prints true because all three expressions return the same object. The expressions are not interchangeable, though.
| Expression | Needs | Resolved | Result type | Failure |
|---|---|---|---|---|
| `String.class` | the type name in source | at compile time | `Class<String>` | compile error if the type is missing |
| `obj.getClass()` | an object | at run time | `Class<? extends X>`, where `X` is the static type of `obj` | `NullPointerException` if `obj` is null |
| `Class.forName("...")` | a name as a string | at run time | `Class<?>` | `ClassNotFoundException` (checked) |
Class literals
String.class is checked by the compiler. Use it whenever you know the type when you write the code. It also works for primitives and void: int.class and void.class are valid. Each wrapper class has a TYPE field that holds the same object, so Integer.TYPE == int.class. Note that int.class != Integer.class. This matters when you look up a method such as Math.abs(int): you must pass int.class, not Integer.class.
getClass()
getClass() returns the runtime type of an object, which may be a subclass of its declared type:
Object o = new java.util.ArrayList<String>();
System.out.println(o.getClass().getName());This prints java.util.ArrayList, even though the variable is declared as Object. getClass() is declared final on Object, so no class can override it to lie about its type. It also works only on references, so a primitive needs a class literal.
Class.forName()
Class.forName takes a name that can come from a configuration file, a command-line argument, or a plugin list. It is the entry point when the type is not known until run time. The name must be the binary name, as returned by getName(). For a nested class that means java.util.Map$Entry, with a dollar sign. For an array it means the encoded form shown below.
The class must be on the classpath, or ClassNotFoundException is thrown. This is a checked exception, so you must catch or declare it.
Loading versus initialization
A type goes through loading, linking, and initialization. Initialization runs static initializers and sets static fields. The one-argument Class.forName loads the type and initializes it. A class literal loads it but does not initialize it. The three-argument form lets you choose:
class Eager {
static { System.out.println("Eager initialized"); }
}
class Lazy {
static { System.out.println("Lazy initialized"); }
}
public class LoadDemo {
public static void main(String[] args) throws Exception {
Class<?> literal = Eager.class;
System.out.println("got literal");
Class.forName("Eager");
System.out.println("loaded Eager");
ClassLoader loader = LoadDemo.class.getClassLoader();
Class<?> lazy = Class.forName("Lazy", false, loader);
System.out.println("got Lazy without init");
lazy.getDeclaredConstructor().newInstance();
}
}Save the code as LoadDemo.java in a directory with no package line. The output is:
got literal
Eager initialized
loaded Eager
got Lazy without init
Lazy initializedEager is initialized by the forName call, not by the literal. Lazy is initialized only when the first instance is created.
Where the three paths lead
Reading names correctly
A Class object offers several name methods, and they return different strings. Run this to see them side by side:
import java.util.Map;
public class NameDemo {
public static void main(String[] args) {
Class<?>[] types = { int[].class, String[].class, Map.Entry.class, int.class };
for (Class<?> t : types) {
System.out.println(t.getName() + " | " + t.getSimpleName()
+ " | " + t.getCanonicalName());
}
}
}The output is:
[I | int[] | int[]
[Ljava.lang.String; | String[] | java.lang.String[]
java.util.Map$Entry | Entry | java.util.Map.Entry
int | int | intgetName()returns the binary name. This is the stringClass.forNameaccepts. Arrays use a JVM encoding:[Iis an array ofint, and[Ljava.lang.String;is an array ofString.getSimpleName()returns the name without the package. It is meant for display, not for lookup.getCanonicalName()returns the name as you would write it in source. It isnullfor anonymous and local classes, so do not use it as a key.
First look at the type's shape
Once you have a Class object, a few methods describe where the type sits in the hierarchy:
getSuperclass()returns the direct superclass. It returnsnullforObject, for interfaces, for primitives, and forvoid.getInterfaces()returns only the interfaces declared directly on that type, not those inherited from a superclass.isInterface(),isArray(),isPrimitive(),isEnum(), andisAnnotation()classify the type.getComponentType()returns the element type of an array, andnullfor anything else.isInstance(obj)is the runtime form ofinstanceof, andisAssignableFrom(other)tests whetherothercan be assigned to this type.
public class HierarchyDemo {
public static void main(String[] args) {
System.out.println(Number.class.isAssignableFrom(Integer.class));
System.out.println(Integer.class.isAssignableFrom(Number.class));
System.out.println(Number.class.isInstance(42));
System.out.println(int[].class.getComponentType());
}
}This prints true, false, true, and int. Read A.isAssignableFrom(B) as "can a value of type B go into a variable of type A".
Common errors
- Wrong name format.
Class.forName("Map.Entry")fails. Usejava.util.Map$Entry, and always include the package. - Calling
getClass()on null. This throwsNullPointerException. A class literal never has this problem. - Confusing the static and runtime type.
getClass()reports what the object is, not what the variable says. Code that comparesgetClass() == Foo.classrejects subclasses, which is sometimes intended (inequals) and sometimes a bug. - Comparing
Classobjects across loaders. Two loaders can each load a class with the same name, and the results are differentClassobjects. They fail==and cause confusingClassCastExceptionmessages such as "X cannot be cast to X". - Unintended initialization. If a static initializer has side effects, a one-argument
forNameruns them. Passfalsefor the second argument if you only need to inspect the type.
Exercise
What does each line print, and why? Class<?> x = Class.forName("java.util.Map.Entry"); and Object o = "text"; System.out.println(o.getClass() == Object.class);
Show answer
The first line throws ClassNotFoundException. Class.forName needs the binary name, which for a nested type uses a dollar sign: java.util.Map$Entry. The second prints false. getClass() returns the runtime type, which is String.class, not the declared type Object. Object.class is a different Class object.
Exercise
You write Class.forName("Config", false, loader) to check that a class exists. A colleague says this is safer than Class.forName("Config"). What is the difference, and when does it matter?
Show answer
The three-argument form with false loads the class but does not run its static initializer. The one-argument form also initializes the class. This matters when the static initializer has side effects, such as opening connections or registering drivers, or when it can throw an error. With false, you can inspect the type without triggering them.