java之反射
反射的最大好处就是可扩展性。。。以下为例子实现。。。
因为如果要添加功能,就不再需要改主函数的代码了,只需改动配置文件即可。。。
package heng.java.reflect.notebook;import java.io.File;import java.io.FileInputStream;import java.io.IOException;import java.util.Properties;public class NoteBookMain {public static void main(String[] args) throws IOException, Exception {NoteBook book = new NoteBook();book.run();//book.useUSB(null);//对外提供配置文件。File configFile = new File("usb.properties");if(!configFile.exists()){configFile.createNewFile();}//读取流和配置文件关联FileInputStream fis = new FileInputStream(configFile);Properties prop = new Properties();prop.load(fis);for (int i = 1; i <= prop.size(); i++) {String className = prop.getProperty("usb"+i);Class clazz = Class.forName(className);USB usb = (USB)clazz.newInstance();book.useUSB(usb);}}}
package heng.java.reflect.notebook;public class NoteBook {public void run(){System.out.println("Running");}public void useUSB(USB usb){if(usb != null){usb.close();usb.open();}}}
对外接口:
package heng.java.reflect.notebook;public interface USB {void close();void open();}
功能一:
package heng.java.reflect.notebook;public class MouseByUSB implements USB{public void close(){System.out.println("mouse close");}public void open(){System.out.println("mouse open");}}
功能二:
package heng.java.reflect.notebook;public class KeyByUSB implements USB {@Overridepublic void close() {System.out.println("Key close");}@Overridepublic void open() {System.out.println("Key open");}}
配置文件:
usb1=heng.java.reflect.notebook.MouseByUSBusb2=heng.java.reflect.notebook.KeyByUSB