Class objects can save information of the Java type. It is a bit confusing. Let's talk about it with examples.
The getclass method in the object class returns an instance of the class type. For example
Classtest C;
...
Class Cl = C. getclass ();
The CL object stores some information about the classtest class. The most common class method is getname, which returns the class name in the form of a string. For example, the following code displays the class name string "classtest ":
Public class classtest
...{
Public static void main (string [] ARGs)
...{
Classtest c = new classtest ();
Class Cl = C. getclass ();
System. Out. println (Cl. getname ());
}
}
The static method forname (string) of the class can obtain the class object from a string:
String classname = "Java. util. Date ";
Class Cl = Class. forname (classname );
Another method to obtain class objects is also very easy. If t is of any Java type (not necessarily a class or a basic type such as Int or double), T. Class indicates the corresponding class object.
Class cl1 = int. Class;
Class Cl2 = double []. Class;
Another useful method is newinstance (). It can create an instance of the class it represents from a class object. For example, the following code creates a date object:
String S = "Java. util. Date ";
Object M = Class. forname (s). newinstance ();
The newinstance method calls the default constructor to create an object. If no default constructor exists, an exception is thrown.