动态代理(JDK实现)

JDK动态代理,针对目标对象接口进行代理 ,动态生成接口的实现类 !(必须有接口)

public class ProxyDemo {

    //通过方法的返回值得到代理对象            方法参数是要增强的对象
    public Object getProxyObject(final Object target) {
        
        Object proxyObj = Proxy.newProxyInstance(   //调用Proxy类中的静态方法,创建代理对象
                target.getClass().getClassLoader(),  //参数1:目标对象的类加载器
                target.getClass().getInterfaces(),   //参数2:目标对象实现的接口
                new InvocationHandler() {            //匿名内部类的方式,回调方法,增强对象
                    
                    @Override  //在该方法中写逻辑代码,增强方法
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        System.out.println("前置增强");
                        Object result = method.invoke(target, args);
                        System.out.println("后置增强");
                        return result;
                    }
                });
        return proxyObj;
    }
}

原文地址:https://www.cnblogs.com/shizhongyang/p/7147476.html