Java学习之反射练习

需求:电脑主板,后期扩展具体扩展什么不清楚,但扩展必须具有打开和关闭的功能。

分析:有主板自己运行函数和扩展运行函数,扩展提供了规则,通过反射获取所有符合规则的类

主板代码

 1 public class MainBoard {
 2     public void run() {
 3     System.out.println("main board run...");
 4     }
 5     
 6     public void usePCI(PCI p) {
 7     if(p!=null) {
 8         p.open();
 9         p.close();
10     }
11     }
12 }

扩展的规则接口

1 public interface PCI {
2     public void open();
3     public void close();
4 }

实现扩展的规则接口的实体

 1 public class SoundCard implements PCI {
 2 
 3     @Override
 4     public void open() {
 5     System.out.println("Sound open");
 6     }
 7 
 8     @Override
 9     public void close() {
10     System.out.println("Sound close");
11     }
12 }
 1 public class NetCard implements PCI {
 2 
 3     @Override
 4     public void open() {
 5     System.out.println("net run...");
 6     }
 7 
 8     @Override
 9     public void close() {
10     System.out.println("net run...");
11     }
12 }

增加其扩展性使用反射机制实现:通过配置文件实例化对象

配置文件(pci.properties)

pci1=cn.marw.reflect.test.SoundCard
pci2=cn.marw.reflect.test.NetCard

主程序实现代码

public static void main(String[] args) throws Exception {
    MainBoard mBoard=new MainBoard();
    mBoard.run();
    
    File configFile=new File("pci.properties");
    Properties properties=new Properties();
    FileInputStream fis=new FileInputStream(configFile);
    
    properties.load(fis);
    
    for(int x=0;x<properties.size();x++) {
        String picName=properties.getProperty("pci"+(x+1));
        
        Class clazz=Class.forName(picName);
        
        PCI pci = (PCI) clazz.newInstance();
        
        mBoard.usePCI(pci);
    }
    fis.close();
    }

结果

猜你喜欢

转载自www.cnblogs.com/WarBlog/p/12156357.html