1

When you do:

MyClass.class.someMethod()

What exactly is the "class" field? I can't find it in the API docs. Is it an inherited static field?

I thought reserved keywords were not allowed as entity names.

RBT
  • 24,161
  • 21
  • 159
  • 240
  • Related post - [What does .class mean in Java?](https://stackoverflow.com/q/15078935/465053) & [How does a '.class' property work?](https://stackoverflow.com/q/10076629/465053) – RBT Aug 03 '18 at 00:06
  • Another related post - [Java “.class” property - C# equivalent](https://stackoverflow.com/q/42228180/465053) – RBT Aug 03 '18 at 00:15

4 Answers4

4

Please read :

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. 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. The type of void.class is Class.

Java Language Specification: 15.8.2. Class Literals

Winand
  • 2,093
  • 3
  • 28
  • 48
Amir Afghani
  • 37,814
  • 16
  • 84
  • 124
  • 1
    So the whole expression MyClass.class represents one single thing i.e. it's not a member access. –  Jul 02 '09 at 02:15
2

MyClass is not the name of an object, it's a class name, so this is actually special syntax that retrieves the corresponding Class<MyClass> object for the named class. It is a language feature, not a real property of the MyClass class.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
  • 1
    Class<|MyClass|> where |T| is the raw type of T, actually. If you had a variable `list` of type `List`, `list.class` would return with a type of Class. – Tom Hawtin - tackline Jul 02 '09 at 02:14
2

The .class is not actually a field. You can think of is as more of an 'extension' like a file extension. It is a token used to differentiate the Class Object as opposed to an instance of the class.

akf
  • 38,619
  • 8
  • 86
  • 96
0

This is documented here:

http://java.sun.com/javase/6/docs/api/java/lang/Class.html