0

Cay Horstmann in his book Core Java describes this method for obtaining an object of type Class

If T is any Java type, then T.class is the matching class object. For example:

Class cl1 = Date.class; // if you import java.util.*; 
Class cl2 = int.class; 
Class cl3 = Double[].class; 

Note that a Class object really describes a type, which may or may not be a class. For example, int is not a class, but int.class is nevertheless an object of type Class.

I've scanned through java.util and can't explain what is written here. That "class" seems to be a field. A field of an Object class. Though it contradicts to what is written by Mr. Horstmann who references to java.util. Could you point at where can I read about it in javadoc?

halfer
  • 19,824
  • 17
  • 99
  • 186
Michael
  • 4,273
  • 3
  • 40
  • 69

2 Answers2

2
// if you import java.util.*; 

The Date class is in java.util, so you need to import it. That statement has nothing to do with class literals, which is what the syntax of TypeName.class is called.

What is a class literal in Java?

Class literals in the Java Language Specification.

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.

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

Community
  • 1
  • 1
Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
2

It's not in javadoc because it's not a method you call - it's part of the syntax of the language. It's a class literal, which is described in the Java Language Specification section 15.8.2:

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 C.class, where C is the name of a class, interface, or array type (§4.3), is Class<C>.

The type of p.class, where p is the name of a primitive type (§4.2), is Class<B>, where B is the type of an expression of type p after boxing conversion (§5.1.7).

The type of void.class (§8.4.5) is Class<Void>.

Community
  • 1
  • 1
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194