the reflection mechanism in Java is a technique that greatly enhances the program extensibility. When a program encapsulation is completed (generate EXE file), if you want to extend the function of the program, do not have to make the code from the new modification (also impossible to get the source), as long as the configuration file (usually XML) can be done.
Such a program provides an external interface , as long as the rules of the interface define an object (function), you can extend the function for the application.
In this analogy, you buy a computer motherboard (a packaged program ), and you want to add a sound card ( the functionality to extend ), which can only be extended through a PCI interface (an application-provided interface). The interface of the sound card must conform to the PCI rules before it can be used by the motherboard. Extend functionality by adding drivers ( modifying XML configuration Files ).
Specific to the code implementation is divided into the following steps:
1, define an interface (PCI) and a series of methods to use as load function.
2. Define an object and implement the interface, and make a copy of the method.
3. Add the name key value pair for the object in the configuration file.
4, the definition of an input stream, read into the configuration file into the properties set (robustness judgment);
5. Use the For loop to get the object name in the properties set.
6. After obtaining the name, load the class with class and instantiate an object (which can be typed strongly, because the PCI interface is known).
7, use the object.
1 File configfile =NewFile ("Pci.properties"); 2 3 Properties prop =NewProperties ();4 FileInputStream FIS =NewFileInputStream (configfile);5 6prop.load (FIS);7 8 for(intx=0; X<prop.size (); X + +){ 9 String pciname = Prop.getproperty ("PCI" + (x+1));Class clazz = Class.forName (pciname);//use class to load this PCI subclass. PCI P = (PCI) clazz.newinstance ();//The PCI interface is already defined, with open and close two methodsMB.USEPCI (P);//MB is a motherboard object that defines a method that uses the PCI interface17 }Fis.close ();
A summary of the reflection mechanism in Java