通过多态完成反射类似功能
public class Demo_Reflect {
public static void main(String[] args) throws ClassNotFoundException {
Juicer j = new Juicer();
j.run(new Apple());// 榨苹果汁
j.run(new Orange());// 炸橘汁
}
}
interface Fruit {
public void squeeze();// 榨汁
}
class Apple implements Fruit {
@Override
public void squeeze() {
System.out.println("榨出一杯苹果汁");
}
}
class Orange implements Fruit {
@Override
public void squeeze() {
System.out.println("榨出一杯橘汁");
}
}
class Juicer {
public void run(Fruit f) {
f.squeeze();// 执行榨汁
}
}