What is the importance of "Java.lang.Class" in Java?


The java.lang.Class is one of the most important class in Java and it can provide several utility methods like getClass(), forName() which is used to find and load a class. It can also provide methods like Class.newInstance() which is the backbone of reflection and allow us to create an instance of a class without using new() operator.

Importance of java.lang.Class

  • Instances of the class Class represent classes, interfaces, enum and annotation in a running Java application.
  • Whenever a java file is compiled, the compiler will insert a public, static, final field named Class of the type java.lang.Class into generated .class file
  • Each and every class exposes its code in the form of an instance of java.lang.Class.
  • The Class has no public constructor. Instead, Class objects are constructed automatically by the Java Virtual Machine (JVM) as classes are loaded and by calls to the defineClass() method in the class loader.

Example

Live Demo

public class TutorialsPoint {
   public static void main(String []args){
      //accessing getName() method via class field.
      System.out.println("The name of the class is: "+ TutorialsPoint.class.getName());
   }
}

Output

The name of the class is: TutorialsPoint
raja
Published on 18-Jun-2019 13:01:54
Advertisements