Class.ForName()读取配置文件

  • 榨汁机(Juicer)榨汁的案例
  • 分别有水果(Fruit)苹果(Apple)香蕉(Banana)桔子(Orange)榨汁(squeeze)

  • public class Demo_Reflect {
    
        /**
         * 榨汁机(Juicer)榨汁的案例
         * 分别有水果(Fruit)苹果(Apple)香蕉(Banana)桔子(Orange)榨汁(squeeze)
         * @throws Exception 
         */
        public static void main(String[] args) throws Exception {
            /*Juicer j = new Juicer();
            //j.run(new Apple());
            j.run(new Orange());*/
            BufferedReader br = new BufferedReader(new FileReader("config.properties"));    //创建输入流对象,关联配置文件
            Class<?> clazz = Class.forName(br.readLine());                                  //读取配置文件一行内容,获取该类的字节码对象
            Fruit f = (Fruit) clazz.newInstance();                                          //通过字节码对象创建实例对象
            Juicer j = new Juicer();
            j.run(f);
        }
    
    }
    interface Fruit {
        public void squeeze();
    }
    
    class Apple implements Fruit {
        public void squeeze() {
            System.out.println("榨出一杯苹果汁儿");
        }
    }
    
    class Orange implements Fruit {
        public void squeeze() {
            System.out.println("榨出一杯桔子汁儿");
        }
    }
    
    class Juicer {
        public void run(Fruit f) {
            f.squeeze();
        }
    
    }
    

     

     

posted on 2017-02-17 19:18  LoaderMan  阅读(606)  评论(0编辑  收藏  举报

导航