How to obtain a class object in Java?

In Java, there are multiple ways to obtain a Class object.

  1. Get the Class object of an object using the getClass() method. For example:
String str = "Hello";
Class<?> strClass = str.getClass();
  1. Retrieve the Class object of a class using the class field of the class. For example:
Class<?> stringClass = String.class;
  1. For example, use the forName() method of the Class class to obtain a Class object based on the fully qualified name of the class.
Class<?> stringClass = Class.forName("java.lang.String");

It is worth noting that the third method requires providing the fully qualified name of the class and also handling the ClassNotFoundException exception.

bannerAds