jdk動態代理舉例


JDK動態代理是基於接口的代理,下面舉例說明

  • 代理類:proxy,代理動作必須要基於一個proxy實例來執行
  • 代理執行類:實現InvocationHandler,案例中是TestInvocationHandler
  • 被代理類:基於接口的用戶自己的方法,案例中是SayImpl

首先說明下InvocationHandler的invoke

public interface InvocationHandler {
  public Object invoke(Object proxy, Method method, Object[] args)
          throws Throwable;
}

proxy:方法基於哪個proxy實例來執行

method:執行proxy實例的哪個方法(proxy代理誰就執行誰的方法)

args:methed的入參

 

代碼示例:

public interface Say {
    void sayHello(String words);
}
public class SayImpl implements Say {
    @Override
    public void sayHello(String words) {
        System.out.println("hello:" + words);
    }
}
public class TestInvocationHandler implements InvocationHandler {

    private Object target;
    public TestInvocationHandler(Object target) {
        this.target=target;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("invoke begin");
        System.out.println("method :"+ method.getName()+" is invoked!");
        method.invoke(target,args);
        System.out.println("invoke end");
        return null;
    }
}
    public static void main(String[] args) {

        TestInvocationHandler testInvocationHandler = new TestInvocationHandler(new SayImpl());
        Say say = (Say)Proxy.newProxyInstance(SayImpl.class.getClassLoader(), SayImpl.class.getInterfaces(), testInvocationHandler );
        say.sayHello("my dear");
    }

 

執行結果:

invoke begin
method :sayHello is invoked!
hello:my dear
invoke end

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM