I. Class
1. The class Object describes the running classes and interfaces. You can use the Class object to obtain information about the running classes and interfaces.
2. Each class has a corresponding Class object. The class Object of each Class is stored in the file where the compiled class is located. Therefore, when the JVM loads a. class file, it loads a Class object. Therefore, a class has only one Class object.
Ii. Basic Application of the Class
1. How to obtain a class Object of A Class
1.1 using the Class. forName (classname) method, this method receives a String parameter to specify the class Object of the Class to be generated, such as Class. forName ("Dog ").
1.2 It is obtained through class literals.
1) the literal constant is in the form of classname. class. For example, Dog. class.
2) for basic classes, each basic TYPE of overwriting Class has a standard data named TYPE, which can generate a reference pointing to the corresponding basic TYPE of Class Object. For example, int. class is equivalent to Integer. TYPE.
1.3 obtained through the Object. getClass () method, as shown in figure
- Dog dog =NewDog ();
- Dog. getClass ();
1.4 example of generating a Class Object
- ClassCat {
- Cat (){System. Out. println ("Init Cat ()");}
- Static{
- System. Out. println ("Loading Cat ");
- }
- }
- ClassDog {
- Dog (){System. Out. println ("Init Dog ()");}
- Static{
- System. Out. println ("Loading Dog ");
- }
- }
- ClassDuck {
- Duck (){System. Out. println ("Init Duck ()");}
- Static{
- System. Out. println ("Loading Duck ");
- }
- }
- Public ClassTest {
- Public Static VoidMain (String[] Args ){
- System. Out. println ("in main ()");
- NewCat ();
- System. Out. println ("After create Cat ()");
- Try{
- ClassC1 =Class. ForName ("Dog ");// (1)
- ClassC2 = Dog.Class;// (2)
- }
- Catch(ClassNotFoundExceptionCnfe ){
- Cnfe. printStackTrace ();
- }
- System. Out. println ("After Class. forName (" Dog ")");
- Duck d =NewDuck ();
- System. Out. println ("After create Duck ()");
- ClassC3 = d. getClass ();
- System. Out. println ("After Class. forName (" Duck ")");
- }
- }
The running result is:
In main ()
Loading Cat
Init Cat ()
After create Cat ()
Loading Dog
After Class. forName ("Dog ")
Loading Duck
Init Duck ()
After create Duck ()
After Class. forName ("Duck ")
Code (1) (2) generates the class Object of Class Dog, but does not generate the class Dog object.
**: Generating a class object does not produce a Class object.
2. Use Classc object for type comparison
2.1. Direct comparison
The two Class objects, whether compared using the equals () function or directly using the = Operator, compare whether they are of the same type.
2.2. Use the Class. isInstance (object) function for comparison, as shown in figure
- ClassCat {}
- ClassDog {}
- ClassDuck {}
- Public ClassTest {
- Public Static VoidMain (