There are several ways to get an object representing a Class depending on whether the code has access to an instance of the class, the name of a class, a type, or an existing Class.
The .class Syntax
To retrieve a Class instance for a given type the .class syntax could be used:
Class stringClass = String.class;
This is also the easiest way to obtain the Class for a primitive type:
Class intClass = int.class;
And even for void:Class voidClass = void.class;
Retrieve Class from object instance
Object class, that is the base class for any reference type, possess getClass() method. To get Class for a given instance it's enough to call this method:
Class instanceClass = "abc".getClass();
Retrieve Class with a given name
If the fully-qualified name of a class is available, it is possible to get the corresponding Class using the static method Class.forName(). However, this cannot be used for primitive types.
Class forName = Class.forName("java.lang.String");
This syntax can also be used to retrieve Class objects for array classes. In this case, the name consists of the name of the element type preceded by one or more [ characters representing the depth of the array nesting. Where the element types are encoded as:
- boolean – Z
- byte – B
- char – C
- class or interface – Lclassname
- double – D
- float – F
- int – I
- long – J
- short – S
Class doubleArrayClass = Class.forName("[D");
Methods that Return Classes
There are several Reflection APIs which return classes but these may only be accessed if a Class as already been obtained either directly or indirectly, e.g.:
// Returns the super class for the given class
String.class.getSuperclass();
// Returns all the public classes, interfaces, and enums that are members of the class
String.class.getClasses();
// Returns all of the classes interfaces, and enums that are explicitly declared in this class.
String.class.getDeclaredClasses();