1. 程式人生 > >Java動態代理

Java動態代理

throws ice handle main throw int 表示 isp logs

首先我們定義一個接口

技術分享
public interface SayService 
{
    public void say();
}
View Code

接著實現這個接口

技術分享
public class SayImpl implements SayService {

    @Override
    public void say() {
        System.out.println("I want to go shoping.");
    }

}
View Code

定義一個動態代理類了,每一個動態代理類都必須要實現 InvocationHandler 這個接口

技術分享
import
java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; public class DynamicProxy implements InvocationHandler { //我們要代理的真實對象 private Object object; public DynamicProxy(Object object) { this.object = object; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws
Throwable { System.out.println("before go shoping"); //當代理對象調用真實對象的方法時,其會自動跳轉到代理對象關聯的handler對象的invoke方法進行調用 method.invoke(object, args); System.out.println("after go shoping"); return null; } }
View Code

定義測試方法

技術分享
public class TestProxy {

    
public static void main(String[] args) { //要代理的對象 SayService sayImpl = new SayImpl(); //要代理哪個對象,就要將改對象傳進去,最後是通過其真實對象來調用方法的 InvocationHandler handler = new DynamicProxy(sayImpl); //Proxy.newProxyInstance--創建代理對象 //handler.getClass().getClassLoader()---加載代理對象 //sayImpl.getClass().getInterfaces()--為代理對象提供的接口是真實對象所實現的接口,表示我們要代理的是改真實對象,這樣我們就能調用接口中的方法 //handler-關聯上的InvocationHandler這個對象 SayService sayService = (SayService)Proxy.newProxyInstance(handler.getClass().getClassLoader() ,sayImpl.getClass().getInterfaces(), handler); sayService.say(); } }
View Code

控制臺打印的日誌

before go shoping
I want to go shoping.
after go shoping

Java動態代理