Java: Difference between a.getClass() and A.class

a.getClass() returns the runtime type of a. If you for example have A a = new B(); then a.getClass() will return the B class.

A.class evaluates to the A class statically.

Use a.getClass() only if you need the runtime type of a but don’t know it in advance.

Example 1: getClass

To for instance decide if a given Object is of a class in the default package, you could do

boolean isDeclaredInDefaultPkg(Object o) {
    // Type of 'o' unknown. Use getClass.
    return o.getClass().getPackage() == null;
}

Example 2: A.class

Use A.class if you know in advance (when writing the code) which class object you’re interested in. In example below, we’re clearly interested in the DayOfWeek class object.

Set<DayOfWeek> allDays = EnumSet.allOf(DayOfWeek.class);

Comments