package proxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
/**
- 动态代理的举例
- */
interface Human{
String getBelief();
void eat(String food);
}
class SuperMan implements Human{
@Override
public String getBelief() {
return "I belief i can fly!";
}
@Override
public void eat(String food) {
System.out.println("我爱吃"+food);
}
}
public class ProxyTest {
static Object getInstance(Object obj){
MyInvo myInvo = new MyInvo();
myInvo.bind(obj);
return Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(),myInvo);
}
public static void main(String[] args) {
SuperMan superMan = new SuperMan();
Human instance = (Human) ProxyTest.getInstance(superMan);
String belief = instance.getBelief();
System.out.println(belief);
instance.eat("四川麻辣烫!");
}
}
class MyInvo implements InvocationHandler{
private Object obj;
public void bind(Object obj){
this.obj = obj;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {//这里的Object proxy参数干吗用的?
Object invoke = method.invoke(obj, args);
return invoke;
}
}
标签:obj,String,invoke,代码,Object,public,举例,void,宋红康 From: https://www.cnblogs.com/dequanth/p/16821119.html