Is Car.class a “class” of a variable?

Class c1 = Car.class; What is this .class ? Is this a public variable that exists in every class?

+4
source share
3 answers

The .class syntax is the same as the syntax for accessing static fields, but it is not really a static field; This is a special language feature. It is similar to the property of the length array, which is accessed as if it were a field, but was not actually stored as one.

To see the difference, consider this example class:

 class Test { public static Class<Test> myClass = Test.class; } 

Running javap Test gives

 class Test { public static java.lang.Class<Test> myClass; Test(); static {}; } 

As you can see, Test.myClass is stored as a static field, since we ourselves declared it, but Test.class not displayed, because it is not actually stored as a static field.

+5
source

This is special syntax for getting the corresponding Class object. Class is a keyword, so no, there is no property called "class", it's just a syntax shortcut, similar to accessing properties. Like it

 Class.forName("Car") 

except that it does not throw an exception.

+4
source

Each object in Java belongs to a specific class. Therefore, the Object class, which is inherited by all other classes, defines the getClass () method.

getClass() , or class-literal - Foo.class returns a Class object that contains some metadata about the class:

  • name
  • package
  • Methods
  • fields
  • Constructors
  • annotations

and some useful methods such as casting and various checks (isAbstract (), isPrimitive (), etc.). javadoc shows exactly what information you can get about the class.

It points to an instance of Class from the class name. If you have an object of the same class, you can also use

 Class c1 = Class.forName("Car"); 
+3
source

All Articles