0
点赞
收藏
分享

微信扫一扫

一文彻底教会你玩转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();
}
}

运行效果展示

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

代码归总

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;
}
}

 

举报

相关推荐

0 条评论