In Java what pros/cons exist surrounding the choice to use a.getClass()
or A.class
? Either can be used wherever a Class<?>
is expected, but I imagine that there would be performance or other subtle benefits to using both in different circumstances (just like there are with Class.forName()
and ClassLoader.loadClass()
.
getClass() method returns the runtime class of an object. That Class object is the object that is locked by static synchronized methods of the represented class.
The Java Object getClass() method returns the class name of the object.
Coming to the point, the key difference between them is that getClass() only returns true if the object is actually an instance of the specified class but an instanceof operator can return true even if the object is a subclass of a specified class or interface in Java.
The getName() method of java Class class is used to get the name of the entity, and that entity can be class, interface, array, enum, method, etc. of the class object.
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 of a
. I.e., if you have A a = new B();
then a.getClass()
will return the B
class.
A.class
evaluates to the A
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With