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 ]
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.
[ August 16, 2007: Message edited by: Ilja Preuss ]