需求

有如下动物类和动物工厂类,分别创建动物类对象。
动物类
image.png

  1. //动物
  2. interface Animal {
  3. public void eat();
  4. }
  5. class Cat implements Animal {
  6. @Override
  7. public void eat() {
  8. System.out.println("猫吃鱼");
  9. }
  10. }
  11. class Dog implements Animal {
  12. @Override
  13. public void eat() {
  14. System.out.println("狗吃肉");
  15. }
  16. }
  17. class Monkey implements Animal {
  18. @Override
  19. public void eat() {
  20. System.out.println("猴子吃香蕉");
  21. }
  22. }

工厂类
image.png

  1. interface Factory {
  2. public Animal createAnimal();
  3. }
  4. class CatFactory implements Factory{
  5. @Override
  6. public Animal createAnimal() {
  7. return new Cat();
  8. }
  9. }
  10. class DogFactory implements Factory {
  11. @Override
  12. public Animal createAnimal() {
  13. return new Dog();
  14. }
  15. }
  16. class MonkeyFactory implements Factory {
  17. @Override
  18. public Animal createAnimal() {
  19. return new Monkey();
  20. }
  21. }

未使用反射时

  1. @Test
  2. public void demo1(){
  3. Factory factory = new DogFactory(); //创建榨汁机
  4. Animal animal = factory.createAnimal();
  5. animal.eat();//狗吃肉
  6. factory = new CatFactory();//创建榨汁机
  7. animal = factory.createAnimal();
  8. animal.eat();//猫吃鱼
  9. }

使用Class.forName API 创建实例

  1. @Test
  2. public void demo2() throws ClassNotFoundException, InstantiationException, IllegalAccessException {
  3. Class clazz = Class.forName("cn.giteasy.reflect.DogFactory");
  4. Factory factory = (Factory) clazz.newInstance();
  5. Animal animal = factory.createAnimal();
  6. animal.eat();
  7. }

读取配置文件创建类的实例

  1. cn.giteasy.reflect.MonkeyFactory
  2. cn.giteasy.reflect.CatFactory
  3. cn.giteasy.reflect.DogFactory
    @Test
    public void demo3() throws ClassNotFoundException, InstantiationException, IllegalAccessException, IOException {
        //需要修改要创建的类时,只需要修改配置文件即可
        BufferedReader br = new BufferedReader(new FileReader("config.properties"));
        Class clazz;
        Factory factory;
        List<String> list = br.lines().collect(Collectors.toList());
        for (String line : list) {
            clazz = Class.forName(line); //获取该类的字节码文件
            factory = (Factory) clazz.newInstance();//创建实例对象
            Animal animal = factory.createAnimal();
            animal.eat();
        }

        /**
         * 输出结果:
         *
         * 猴子吃香蕉
         * 猫吃鱼
         * 狗吃肉
         */
    }