The reflection mechanism is a very important feature in the Java language, which allows programs to self-check at run time, and also allows internal members to operate. Although this feature is not used much in real-world development, languages such as Pascal, C, and C + + do not provide such a feature at all. Because the reflection mechanism enables the loading of classes at run time, the flexibility of the program can be increased, but improper use of the reflection mechanism can also severely affect the performance of the system.
Specifically, the reflection mechanism provides the following features:
1. Get the class to which an object belongs;
2. Get all the member variables and methods of a class;
3. Create objects at run time;
4. The method of invoking the object at run time.
In fact, one of the most important functions of the reflection mechanism is the ability to dynamically create objects of the class at run time, as in the following example:
1 package cn.ch4; 2 3 class base{ 4 public void F () { 5 System.out.println ("Base"); 6 } 7} 8 class Te extends base{ 9 public void F () { System.out.println ("Te"); One} of the public class Fanshetest {+ public static void Main (string[] args) { 15 try{//uses the reflection mechanism to load class c = class.forname ("cn.ch4.Te");//Note that this is the full path including the package Base B = ( Base) c.newinstance (); B.f (); }catch (Exception e) { e.printstacktrace (); + } 23}
The result of the operation is TE.
In reflection, class is a very important class, and there are three main ways to get the class you want:
1>class.forname ("Path of the Class"), as in the example above;
2> class name. Classes;
3> instance. GetClass ().
A brief introduction to the reflection mechanism of Java