programs run through configuration files, what users configure, what they run, important parts
implementation steps: A Prepare the configuration file collection class properties to do
B using IO streaming technology, associating collection classes, reading configuration files
C getting user-configured classes and methods through a configuration file
D reflection Gets the byte-code file object of the user-configured class
E Gets the methods in the class. and run
Data bean:
Student
Package Com.mth.bean;
public class Student {public
Void study () {
System.out.println) ("Student learning.") ");
}
}
Worker
Package Com.mth.bean;
public class Worker {public
void work () {
System.out.println) ("Workers work to make money.") ");
}
}
Config.txt
Classname=student
Methodname=study
Test class:
Package com.mth.test;
Import Java.io.FileInputStream;
Import java.io.FileNotFoundException;
Import Java.lang.reflect.Method;
Import java.util.Properties;
* * *
using the configuration file Config.txt
the * Properties
class represents a persistent set of properties. Properties can be saved in the stream or loaded from the stream.
* Each key and its corresponding value in the attribute list is a string. Key value Pairs
* *
/public class Reflecttest {public
static void Main (string[] args) throws Exception {
//Set Object
Properties proc = new properties ();
Byte input stream to read the configuration file
FileInputStream in = new FileInputStream ("Config/config.txt");
Collection IO Association (This step gets the configuration file)
proc.load (in);
System.out.println (Proc.getproperty ("ClassName"));//Student
System.out.println (Proc.getproperty (" MethodName "));//study
string className = Proc.getproperty (" ClassName ");//class name
String methodname = Proc.getproperty ("methodname");//Method name
Class clazz = Class.forName ("Com.mth.bean." + className);
Object obj = clazz.newinstance ();
Method method = Clazz.getmethod (methodname);
Method.invoke (obj);
}
Program Run Result:
Change configuration file does not modify code program run results:
Config.txt
Classname=worker
Methodname=work