首页 > 代码库 > java动态代理实例

java动态代理实例

import java.lang.reflect.InvocationHandler;import java.lang.reflect.Method;import java.lang.reflect.Proxy;public class ProxyTest {    public static void main(String[] args) {        Target target = (Target)Proxy.newProxyInstance(TargetImpl.class.getClassLoader(), TargetImpl.class.getInterfaces(), new MyInterceptor());        target.say();        /*         Console:            拦截之前            this is Target.class            拦截之后         */    }}//目标类接口interface Target {    void say();}//目标类class TargetImpl implements Target {    @Override    public void say() {        System.out.println("this is Target.class");    }}//拦截器class MyInterceptor implements InvocationHandler {    private Object target = new TargetImpl();        @Override    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {        System.out.println("拦截之前");        method.invoke(target, args);//调用目标类方法        System.out.println("拦截之后");        return null;    }}

 

java动态代理实例