Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getclass() vs .class [duplicate]

Tags:

java

Possible Duplicate:
What’s the difference between calling MyClass.class and MyClass.getClass()

Wanting to have a Class<T> object, Which is the difference between these two approaches?

Test ob = new Test();

ob.getclass();

or

Test.class
like image 335
jacktrades Avatar asked Nov 13 '12 19:11

jacktrades


2 Answers

As per Class javadoc

First approach get Class object from Object.

second approach get Class object for a named type (or for void) using a class literal.

like image 186
kosa Avatar answered Sep 18 '22 12:09

kosa


The getClass() method is defined in java.lang.Object and hence can be called on any object reference.

It gets the Class object associated with the run-time type of the object to which the reference points. .

The getClass() method is not really analogous to .class at all. Closer is Class.forName(String), which gets a Class object for the class named by the String.

In situations where either could be used, use .class , as it is more efficient.

like image 20
Mukul Goel Avatar answered Sep 20 '22 12:09

Mukul Goel