What is the difference between a.getClass() and A.class in Java?
I wouldn't compare them in terms of pros/cons since they have different purposes and there's seldom a "choice" to make between the two.
a.getClass()
returns the runtime type ofa
. I.e., if you haveA a = new B();
thena.getClass()
will return theB
class.A.class
evaluates to theA
class statically, and is used for other purposes often related to reflection.
In terms of performance, there may be a measurable difference, but I won't say anything about it because in the end it is JVM and/or compiler dependent.
This post has been rewritten as an article here.
They are actually different with regards to where you can use them. A.class
works at compile time while a.getClass()
requires an instance of type A
and works at runtime.
There may be a performance difference as well. While A.class
can be resolved by the compiler because it knows the actual type of A
, a.getClass()
is a virtual method call happening at runtime.
For reference, a compiler targeting bytecode typically emits the following instructions for Integer.getClass()
:
aload_1
invokevirtual #3; //Method java/lang/Object.getClass:()Ljava/lang/Class;
and the following for Integer.class
:
//const #3 = class #16; // java/lang/Integer
ldc_w #3; //class java/lang/Integer
The former would typically involve a virtual method dispatch and therefore presumably take longer time to execute. That is in the end JVM-dependent however.
have a look at the examples below
a.getClass()!= A.class
, i.e. a is not an instance of A but of an anonymous sub class
of A
a.getClass()
requires an instance of type A
Use a.getClass
when you have an instance of class/type and you want to get exact type of it. while a.class
is used when you have type
available and you want to create instance of it.
Also getClass()
returns runtime type of instance while .class
is evaluated at compile time.
Considering performance of getClass()
and.class
,.class
has better performance than getClass()
.
Example :
public class PerfomanceClass {
public static void main(String[] args) {
// TODO Auto-generated method stub
long time=System.nanoTime();
Class class1="String".getClass();
class1="String".getClass();
class1="String".getClass();
class1="String".getClass();
System.out.println("time (getClass()) :"+(System.nanoTime()-time)+" ns");
long time2=System.nanoTime();
Class class2=String.class;
class2=String.class;
class2=String.class;
class2=String.class;
System.out.println("time (.class):"+(System.nanoTime()-time2)+" ns");
}
}
Output :
time (getClass()) : 79410 ns
time (.class) : 8032 ns