通过榨汁机学习反射
修身,齐家,治国,平天下。
水果接口
public interface Fruit {
void juice();
}
实现类
class Apple implements Fruit{
@Override
public void juice() {
// TODO Auto-generated method stub
System.out.println("苹果汁");
}
}
class Banana implements Fruit{
@Override
public void juice() {
// TODO Auto-generated method stub
System.out.println("香蕉酱");
}
}
榨汁机
public class Juicer {
public void runJuicer(Fruit f) {
System.out.println("榨汁机开始工作————咕咕咕咕");
f.juice();
}
}
测试类
import java.lang.reflect.Method;
public class JuiceRef {
public static void main(String[] args) throws Exception {
Class<?> clazz = Class.forName("day22.Juicer");
Object newInstance = clazz.newInstance();
Method method = clazz.getDeclaredMethod("runJuicer", Fruit.class);
method.invoke(newInstance, new Apple());
}
}