In the past, if we wanted to invoke a method in a class, it would only look like this:
Cases:
There are two classes of cat and dog, with eat and run two member methods:
1 Public classDog {2 3 Public voideat () {4System.out.println ("Dog eats meat");5 }6 7 Public voidrun () {8System.out.println ("Dog planing"));9 }Ten}
Public class Cat { publicvoid eat () { System.out.println ("Cat eats Fish"); } Public void run () { System.out.println ("cat Tree Climbing");} }
Before, if you want to invoke a method inside a class, you can only do this:
To do so, there is a drawback, if the class more, the method is more, later changes are very troublesome.
1 // the previous practice 2 New Cat (); 3 c.eat (); 4 C.run (); 5 6 New Dog (); 7 d.eat (); 8 D.run ();
So, for the convenience of future changes.
Create a corresponding configuration file and use reflection to access these methods:
Configuration file: (The Properties
class represents a persisted set of properties.) Inside the content is the key value of "AAAA=BBB")
Cases:
1 classname=zl_reclfect_05.cat2 methodname=eat
Create a reflective class to invoke the methods in the class through the configuration file:
After that you want to invoke which class of which method, only need to go to configure the file to change the corresponding key value is OK.
1 //reflection of the procedure2 3 //Properties Class:4 //C, public string GetProperty (string key): Gets the value based on the key5 6 //Load key value pair data7 8 //first create a property set class9Properties p =NewProperties ();Ten //encapsulating the configuration file OneFileReader file =NewFileReader ("Class.txt"); A //gets the collection of keys - //void Load (InputStream instream) reads the list of attributes (key and element pairs) from the input stream. - p.load (file); the file.close (); - - //get the value of the key (do the configuration file, definitely know the key) -String classname = P.getproperty ("classname"); +String methodname = P.getproperty ("methodname"); - + //to invoke a member method with reflection A at //get byte file object -Class C =Class.forName (classname); - - //create an object without a parameter construct -Constructor con =c.getconstructor (); -Object obj =con.newinstance (); in - //Calling Methods toMethod m =C.getmethod (methodname); + M.invoke (obj); - the //after that you want to invoke which class of which method, only need to go to configure the file to change the corresponding key value is OK.
Java 27-6 reflection of methods in running a class through a configuration file