一個接口代理demo

 

說明: 自定義一個接口,動態生成代理類並執行java

核心代碼爲 java提供api

Proxy

的api:ide

public static Object newProxyInstance(ClassLoader loader,
                                      Class<?>[] interfaces,
                                      InvocationHandler h)

 

核心代碼:測試

import com.ahd.feign.intef.UserInte;
import java.lang.reflect.Proxy;

public class ProxyTest {
    public static void main(String[] args) {
        System.out.println(UserInte.class.isInterface());//isInterface 判斷是不是接口,UserInte即自定義的接口

        Object o = Proxy.newProxyInstance(UserInte.class.getClassLoader()//自定義接口 UserInte 的類加載器
                , new Class[]{UserInte.class}//自定義接口的class對象
                , new MyInvocationHandler());//自定義的實現 InvocationHandler的調用處理類
        
        UserInte userInte = (UserInte)o;
        
        userInte.test(); //自定義接口用來測試的方法
    }
}

 

自定義接口 UserInte 代碼(被代理的接口):this

public interface UserInte {

    public void test();

}

 

自定義InvocationHandler類,重寫 invoke方法
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
public class MyInvocationHandler implements InvocationHandler {
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Object invoke = null;

        //若是傳進來的是一個接口(核心)
        if (method.getDeclaringClass().isInterface()) {
            try {
                //能夠作一系列代理操做
                //如調用方法
                //如遠程http操做
                //這裏測試只打印一句話
                System.out.println("接口調用成功");
            } catch (Throwable t) {
                t.printStackTrace();
            }
        //若是傳進來是類
        } else {
            try {
                invoke = method.invoke(this, args);
            } catch (Throwable t) {
                t.printStackTrace();
            }
        }
        return invoke;
    }
}

 

效果:

相關文章
相關標籤/搜索