public interface Human {
public String getBelief();
void eat(String food);
}
public class MyInvocationHandler implements InvocationHandler {
private Object object;
public void bind(Object o) {
this.object=o;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object returnvalue=method.invoke(object,args);
return returnvalue;
}
}
public class ProxyFactory {
public static Object getProxyInstance(Object o){
MyInvocationHandler handler=new MyInvocationHandler();
handler.bind(o);
return Proxy.newProxyInstance(o.getClass().getClassLoader(),o.getClass().getInterfaces(), handler);
}
}
public class SuperMan implements Human{
@Override
public String getBelief() {
return "fly";
}
@Override
public void eat(String food) {
System.out.println("我喜欢吃"+food);
}
}
public class Test {
public static void main(String[] args) {
SuperMan superMan=new SuperMan();
Human human=(Human) ProxyFactory.getProxyInstance(superMan);
String belief=human.getBelief();
System.out.println(belief);
human.eat("麻辣烫");
}
}