笔记本类:
package cn.fanse; public class Notebook { public void run() { System.out.println("book run"); } public void useUSB(USB usb) { usb.open(); usb.close(); } }
USB接口:
package cn.fanse; public interface USB { public void open(); public void close(); }
鼠标实现USB接口:
package cn.fanse; public class MousebyUSB implements USB{ @Override public void open() { System.out.println("mouse run"); } @Override public void close() { System.out.println("mouse close"); } }
键盘实现USB:
package cn.fanse; public class KeybyUSB implements USB{ @Override public void open() { System.out.println("key run"); } @Override public void close() { System.out.println("key close"); } }
主函数类:
package cn.fanse; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.Properties; public class notbookdemmo { /** * @param args * @throws Exception */ public static void main(String[] args) throws Exception { Notebook book = new Notebook(); book.run(); File config = new File("usb.properties"); if(!config.exists()) { config.createNewFile(); } FileInputStream fis = new FileInputStream(config); Properties prop =new Properties(); prop.load(fis); for(int x =1;x<=prop.size();x++) { String className = prop.getProperty("usb"+x); Class clazz=Class.forName(className); USB usb =(USB)clazz.newInstance(); book.useUSB(usb); } } }
配置文件:
在配置文件usb.properties 中 编写以下:
usb1=cn.fanse.MousebyUSB
usb2=cn.fanse.KeybyUSB
结果:
book run
mouse run
mouse close
key run
key close
版权声明:本文为博主原创文章,未经博主允许不得转载。
时间: 2024-09-29 01:13:00