Knowledge Point IO Stream applied to set properties reflection
Create a new file Config.properties in the project directory
#one time only can run one methodclassname=demo03. Studentmethodname=study#classname=demo03. Person#methodname=eat#classname=demo03. Work#methodname=job
Create three class person Worker Student
Package demo03; Public class Student { publicvoid study () { System.out.println ("Student is learning");} }
Package demo03; Public class Person { publicvoid eat () { System.out.println ("People are eating ... "); }}
Package demo03; Public class Worker { publicvoid Job () { System.out.println ("office worker is working");} }
Testing class Test
Packagedemo03;Importjava.io.FileNotFoundException;ImportJava.io.FileReader;Importjava.io.IOException;ImportJava.lang.reflect.Method;Importjava.util.Properties;/** Call the person method, call the student method, call the Worker method * class is not clear, the method is not clear * through the configuration file implementation of this function * run the class name and method name, in the form of key-value pairs, written in the text * run which Class, read the configuration file * Implementation steps: * 1. Prepare configuration file, key value pair * 2.IO Stream read Profile reader * 3. Key-value pairs in the file are stored in the collection Properties * Collection The saved key-value pair is the Thunder and the method name * 4. Gets the class file object of the specified classes * 5.class file object, gets the specified method * 6. Run method*/ Public classTest { Public Static voidMain (string[] args)throwsexception{//IO Stream read configuration fileFileReader fr=NewFileReader ("Config.properties"); //To create a collection objectProperties pro=NewProperties (); //Call collection method load, passing stream objectPro.load (FR); Fr.close (); String ClassName=pro.getproperty ("ClassName"); String MethodName=pro.getproperty ("MethodName"); //reflection Gets the class file object for the specified classesClass c=Class.forName (className); Object obj=c.newinstance (); //gets the specified method nameMethod method=C.getmethod (methodName); Method.invoke (obj); }}
Java executes object methods by reading local files to get reflection method parameters