Object.getClass()
Returns the runtime class of an object.
Available since: Java 1.0
Syntax
public final Class<?> getClass()Return value
Class<?>A Class object with getName() and getSimpleName().
Examples
The actual class of an object, even if the variable has a general type:
void main() {
Object a = "text";
Object b = 42;
List<String> c = new ArrayList<>();
IO.println(a.getClass().getSimpleName());
IO.println(b.getClass().getName());
IO.println(c.getClass().getSimpleName());
}Output:
String
java.lang.Integer
ArrayListNotes
For type checks in regular code instanceof is better: it accepts subclasses. getClass() == Other.class checks for the exact class — sometimes used in equals(). getSimpleName() is handy in error messages: e.getClass().getSimpleName().
See also
- instanceof — Checks whether an object is an instance of a type and binds a variable of that type.
- Object.equals() — Compares objects by meaning. By default it works like ==, so classes override it.
Related recipes
In the tutorial
- Methods of the Object class — The toString, equals and hashCode methods in Java: how to override them and why equals and hashCode always change together.