Class c1 = Car.class; What is this .class ? Is it a public variable which exists in every class ?
The .class syntax is the same as the syntax for accessing static fields, but it isn't actually a static field; it's a special language feature. It's similar to an array's length property, which is accessed as if it were a field but 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 declared it ourselves, but Test.class does not show up since it is not actually stored as a static field.
It's special syntax for getting the corresponding Class object. class is a keyword so no, there's no property called "class", it's just a syntactical shortcut that resembles property access. It's like
Class.forName("Car")
except it doesn't throw an exception.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With