dequanth

导航

宋红康老师关于动态代理举例的代码理解

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;
}

}

posted on 2022-10-24 12:49  dequantianhe  阅读(26)  评论(0编辑  收藏  举报