一个接口代理demo

说明: 自定义一个接口,动态生成代理类并执行

核心代码为 java提供

Proxy

的api:

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 代码(被代理的接口):

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;
    }
}
效果:

原文地址:https://www.cnblogs.com/aihuadung/p/14530006.html