Skip to content

How to use Class<T> in Java?

In Java, the Class<T> class represents the class or interface type of a class at runtime. It is essential for reflection, dynamic class loading, and framework development. It can be used to get information about a class, such as its name, fields, methods, and superclass.


java
public class Main {
  public static void main(String[] args) {
    Class<String> cls = String.class;
    String className = cls.getName();
    System.out.println(className);  // Outputs: "java.lang.String"
  }
}

java
public class Main {
  public static void main(String[] args) throws Exception {
    Class<String> cls = String.class;
    String str = cls.getDeclaredConstructor().newInstance();
    System.out.println(str);  // Outputs: ""
  }
}

Note that creating instances via reflection requires a no-arg constructor. The modern approach uses getDeclaredConstructor().newInstance() instead of the deprecated newInstance() method. If the class lacks a no-arg constructor, you can use Constructor<T> to invoke a specific one. Additionally, reflection instantiation may be blocked by security managers or module restrictions; you might need to call setAccessible(true) on the constructor to bypass access checks.

You can also use Class<T> to get the superclass of a class, get its fields and methods, and perform other reflective operations. For more information, you can check the documentation of the Class<T> class in the Java API.

Do you find this helpful?

Dual-run preview — compare with live Symfony routes.