Is .class a method or field?

后端 未结 3 1104
既然无缘
既然无缘 2020-12-05 07:36

Any class in the java has a .class , I want to know .class is a static method or not? Or it is a public static field?

boolean alwaysTrue = (String.class == C         


        
相关标签:
3条回答
  • 2020-12-05 07:57

    When you write .class after a class name, it references the Class object that represents the given class. .class is used when there isn't an instance of the class available.

    For example, if your class is Print (it is recommended that class name begin with an uppercase letter), then Print.class is an object that represents the class Print on runtime. It is the same object that is returned by the getClass() method of any (direct) instance of Print.

    Print myPrint = new Print();
    System.out.println(Print.class.getName());
    System.out.println(myPrint.getClass().getName());
    
    0 讨论(0)
  • 2020-12-05 08:00

    https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.8.2

    It's neither. It's an expression evaluated at compile time to the Class object for that class.

    0 讨论(0)
  • 2020-12-05 08:20

    Its neither.
    It's a built-in language feature (a class literal) that looks like a public static final field.

    0 讨论(0)
提交回复
热议问题