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 can be used to get information about a class, such as its name, fields, methods, and superclass.
Here's an example of how to use Class<T> to get the name of a class:
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"
}
}You can also use Class<T> to create new instances of a class using the newInstance() method:
public class Main {
public static void main(String[] args) {
Class<String> cls = String.class;
String str = cls.newInstance();
System.out.println(str); // Outputs: ""
}
}Note that the newInstance() method requires that the class has a no-arg constructor, which is a constructor that takes no arguments. If the class does not have a no-arg constructor, you can use the Constructor<T> class to get a specific constructor and use it to create a new instance of the class.
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.