• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

getClass() vs .class

 
fahad siddiqui
Ranch Hand
Posts: 85
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
We can get the Class instance of a class by writing com.db.Manager.class or "com.db.Manager".getClass().
What is the difference between these?
Where is this .class defined and what is it? a variable? definitely not a method.

Please explain.
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
(beginner question, not advanced)

Originally posted by fahad siddiqui:
We can get the Class instance of a class by writing com.db.Manager.class or "com.db.Manager".getClass().
What is the difference between these?
Where is this .class defined and what is it? a variable?


"com.db.Manager".getClass() is almost certainly not going to do what you want. It will give you the instance of java.lang.Class corresponding to the java.lang.String class, because "com.db.Manager" is a String.

The .class syntax is a special bit of syntax for efficiently getting the Class object for the class whose name precedes it (not in quotes) in the source code. It can only be used when the exact class is known at compile time.

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.
[ August 15, 2007: Message edited by: Peter Chase ]
 
fahad siddiqui
Ranch Hand
Posts: 85
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Where can i find the .class implements or something in the source code of java? in which class? in the rt.jar ?
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15216
36
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The ".class" notation is a feature of the Java language itself. It's not something in the standard Java library, so you will not find the source code for it in src.zip (which contains the sources of rt.jar).
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Jesper Young:
The ".class" notation is a feature of the Java language itself.


More specifically, it's called a "class literal" - just as 2.0 is a double literal.

See http://java.sun.com/docs/books/jls/second_edition/html/expressions.doc.html#251530
[ August 16, 2007: Message edited by: Ilja Preuss ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic