File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes question about class instance Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "question about class instance" Watch "question about class instance" New topic

question about class instance

kwame Iwegbue
Ranch Hand

Joined: Sep 02, 2000
Posts: 197
I'm trying to find out what "SomeObject.class" means. In this code from a JUnit test suite for example:

does TestCalculator.class refer to an instance of a TestCalculator class (and in that case why not just say new TestCalculator())
...or does it refer to the class TestCalculator
[ October 24, 2006: Message edited by: kwame Iwegbue ]

Who dares, wins! (SAS motto)
Ken Blair
Ranch Hand

Joined: Jul 15, 2003
Posts: 1078
It is a class literal and refers to the java.lang.Class instance for the class.

15.8.2 Class Literals
A class literal is an expression consisting of the name of a class, interface, array, or primitive type, or the pseudo-type void, followed by a `.' and the token class. The type of a class literal, C.Class, where C is the name of a class, interface or array type, is Class<C>. If p is the name of a primitive type, let B be the type of an expression of type p after boxing conversion (�5.1.7). Then the type of p.class is Class<B>. The type of void.class is Class<Void>.

A class literal evaluates to the Class object for the named type (or for void) as defined by the defining class loader of the class of the current instance.

It is a compile time error if any of the following occur:

* The named type is a type variable (�4.4) or a parameterized type (�4.5) or an array whose element type is a type variable or parameterized type.
* The named type does not denote a type that is accessible (�6.6) and in scope (�6.3) at the point where the class literal appears.
Henry Wong

Joined: Sep 28, 2004
Posts: 20517

The java.lang.Class object is used to describe a particular class. Given any instance, you can get the Class object via the getClass() method call. Or you can get it directly for the Class that you want by using the ".class" variable of that class.

So "TestCalculator.class", is an instance of a java.lang.Class, that describes the TestCalculator class.


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
marc weber

Joined: Aug 31, 2004
Posts: 11343

Also see this Class literals topic in Thinking in Java.

"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
I agree. Here's the link:
subject: question about class instance
It's not a secret anymore!