6

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
Community
  • 1
  • 1
jacktrades
  • 6,766
  • 13
  • 50
  • 80
  • 3
    Duplicate: [http://stackoverflow.com/q/2467970/1225328](http://stackoverflow.com/q/2467970/1225328) – sp00m Nov 13 '12 at 19:15

2 Answers2

7

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.

kosa
  • 63,683
  • 12
  • 118
  • 157
  • I think it is called as class literal notation. Read this http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.8.2 – kosa Nov 13 '12 at 19:19
  • 5
    Besides the link, your answer really doesn't explain much. – Paul Bellora Nov 13 '12 at 19:19
  • @PaulBellora: Edited to add some content, apart from that I am not sure what else I could add, If you have anything to add, feel free to edit my answer. – kosa Nov 13 '12 at 19:24
  • Void is special type in java. – kosa Nov 13 '12 at 19:41
  • 2
    @jacktrades In addition to reference types (including arrays), there are also class literals for each primitive and `void`. These are useful for reflection, for example [`Method.getReturnType()`](http://docs.oracle.com/javase/7/docs/api/java/lang/reflect/Method.html#getReturnType\(\)) for methods that return primitives or void. – Paul Bellora Nov 13 '12 at 19:42
  • 1
    @jacktrades: See this discussion http://stackoverflow.com/questions/2352447/what-is-the-need-of-void-class-in-java – kosa Nov 13 '12 at 19:46
  • Well, `Void` (capitalized) serves a different purpose from `void.class` (which `Void.TYPE` points to). But yeah, that's a good discussion about it. – Paul Bellora Nov 13 '12 at 19:54
5

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.

Mukul Goel
  • 8,317
  • 5
  • 34
  • 72