Package Reflect;import Java.io.file;import Java.io.fileinputstream;import java.io.filenotfoundexception;import Java.io.fileoutputstream;import Java.io.ioexception;import java.util.properties;interface Fruit{public Abstract void eat ();} Class Apple implements Fruit{public void Eat () {System.out.println ("Eat Apple");}} Class Orange implements Fruit{public void Eat () {System.out.println ("Eat orange");}} Class Init{public static Properties Getpro () throws FileNotFoundException, ioexception{properties Pro = new Properties (); File F = new file ("Fruit.properties"), if (F.exists ()) {System.out.println ("with config file! Pro.load (new FileInputStream (f)), or read the key values from the configuration file; Else{system.out.println ("No configuration file! ");p Ro.setproperty (" Apple "," reflect "). Apple ");p ro.setproperty (" Orange "," Reflect.orange ");p Ro.store (new FileOutputStream (f)," FRUIT CLASS ");} return pro;}} Class Factory{public static fruit getinstance (String className) {fruit f = null; try {//by reflection to get fruit instance object F = (fruit) class.fo Rname (ClassName). newinstance ();}catch (Instantiationexception e) {e.printstacktrace ();} catch (Illegalaccessexception e) {e.printstacktrace ();} catch ( ClassNotFoundException e) {e.printstacktrace ();} return f;}} public class Hello {public static void main (string[] args) {try {Properties pro = Init.getpro (); fruit F = factory.getinst Ance (Pro.getproperty ("Apple")); if (f! = null) {f.eat ();}} catch (FileNotFoundException e) {//Todo auto-generated catch Blocke.printstacktrace ();} catch (IOException e) {//Todo Au To-generated catch Blocke.printstacktrace ();}}}
The result is:
There are configuration files!
Eat Apple
Java Reflection sample