1. public interface Animal {
    2. void eat();
    3. }
    1. public class Dog implements Animal {
    2. @Override
    3. public void eat() {
    4. System.out.println("dog eat......");
    5. }
    6. }
    1. public class AnimalFactory {
    2. public static Animal getAnimal(String type) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
    3. // test.demo03.factorymode.Dog
    4. Class<?> aClass = Class.forName(AnimalFactory.class.getPackage().getName() + "." + type);
    5. Object o = aClass.newInstance();
    6. return (Animal) o;
    7. }
    8. }

    // 利用工厂来获取指定的类

    1. public class Main {
    2. public static void main(String[] args) throws IllegalAccessException, InstantiationException, ClassNotFoundException {
    3. Animal dog = AnimalFactory.getAnimal("Dog");
    4. dog.eat();
    5. }
    6. }