一文彻底教会你玩转java动态代理

第一步:定义接口

//第一步:定义接口
interface testIProxy {
    void hello();
}

第二步:实现InvocationHandler接口

class myInvocationHandler implements InvocationHandler{
    
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println(method.getName() + "被代理给执行了");
        return null;
    }
}

第三步:调用

public class Demo {
    public static void main(String[] args) {

        //生成代理类
        testIProxy proxyObj = (testIProxy) Proxy.newProxyInstance(ClassLoader.getSystemClassLoader(), new Class[]{testIProxy.class}, new myInvocationHandler());
        //这句话其实是执行了 myInvocationHandler =》 invoke方法
        proxyObj.hello();
    }
}

运行效果展示

代码归总

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class Demo {
    public static void main(String[] args) {

        //生成代理类
        testIProxy proxyObj = (testIProxy) Proxy.newProxyInstance(ClassLoader.getSystemClassLoader(), new Class[]{testIProxy.class}, new myInvocationHandler());
        //这句话其实是执行了 myInvocationHandler =》 invoke方法
        proxyObj.hello();
    }
}

//第一步:定义接口
interface testIProxy {
    void hello();
}

//第二步:实现InvocationHandler接口
class myInvocationHandler implements InvocationHandler {

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println(method.getName() + "被代理给执行了");
        return null;
    }
}

 


版权声明:本文为qq_41885673原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。