Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between a.getClass() and A.class in Java?

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().

like image 375
IAmYourFaja Avatar asked Jun 08 '12 11:06

IAmYourFaja


People also ask

What is class and getClass in Java?

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.

What is the use of getClass () in Java?

The Java Object getClass() method returns the class name of the object.

What is the difference between getClass and Instanceof in Java?

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.

What does getClass () getName () Do 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.


2 Answers

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.

like image 160
aioobe Avatar answered Nov 09 '22 05:11

aioobe


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.

like image 43
Tomasz Nurkiewicz Avatar answered Nov 09 '22 05:11

Tomasz Nurkiewicz