Java 反射机制 与 工厂设计模式( 二 )

使用泛型解决解决第二个问题 。 【Java 反射机制 与 工厂设计模式】 package DemoRunable.example; import java.io.IOException;public class FileDemo {public staticvoid main(String args []) throws IOException, ClassNotFoundException {System.out.println();IFood food = Fatory.eFood("DemoRunable.example.Break",IFood.class);food.eat();IOther other = Fatory.eFood("DemoRunable.example.OtherOne",IOther.class);other.send();} }interface IFood{public abstract void eat();// 食物核心作用 被食用 }class Break implements IFood{@Overridepublic void eat() {System.out.println("手撕面包");} }class Milk implements IFood{@Overridepublic void eat() {System.out.println("喝牛奶");} } interface IOther{public abstract void send(); } class OtherOne implements IOther{@Overridepublic void send(){System.out.println("开心");} }class OtherTwo implements IOther{@Overridepublic void send(){System.out.println("很开心");} } class Fatory{/*** 因fatory 没有属性 因此定义static方法。* 获取IFood接口实例化对象 , 利用此方法对外隐藏子类*/private Fatory(){} // 工厂类 , 没有产生实例化的意义 , 避免产生实例化对象——构造方法私有化/**** @param className 实例化对象名称* @param clazz 返回实例化对象类型* @param泛型 , 使得工厂类适用所有类型* @return 如果子类存在则返回指定类的接口实例化对象*/public staticT eFood(String className,Class clazz) {T food = null;try {food = (T) Class.forName(className).getDeclaredConstructor().newInstance();} catch (Exception e) {e.printStackTrace();}return food;}}