Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Car.class - is "class" a variable?

Tags:

java

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

like image 835
david blaine Avatar asked Dec 16 '22 11:12

david blaine


2 Answers

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.

like image 124
Daniel Lubarov Avatar answered Jan 04 '23 09:01

Daniel Lubarov


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.

like image 42
John Kugelman Avatar answered Jan 04 '23 09:01

John Kugelman