Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

question about class instance

 
kwame Iwegbue
Ranch Hand
Posts: 197
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Ken Blair
Ranch Hand
Posts: 1078
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
author
Marshal
Pie
Posts: 21357
84
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

Henry
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Also see this Class literals topic in Thinking in Java.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic