企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
#### 动态代理 ``` 1.代理对象,不需要实现接口 2.代理对象的生成,是利用JDK的API,动态的在内存中构建代理对象(需要我们指定创建代理对象/目标对象实现的接口的类型) 3.动态代理也叫做:JDK代理,接口代理 ``` #### 示例: InvocationHandlerImpl ~~~ public class InvocationHandlerImpl implements InvocationHandler { private Object target; public InvocationHandlerImpl(Object target) { this.target = target; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { Object result = null; System.out.println("调用开始....."); result = method.invoke(target, args); System.out.println("调用结束....."); return result; } } ~~~ 测试 ~~~ IUserDao userDao = new IUserDaoImpl(); InvocationHandlerImpl invocationHandler = new InvocationHandlerImpl(userDao); ClassLoader loader = userDao.getClass().getClassLoader(); Class<?>[] interfaces = userDao.getClass().getInterfaces(); IUserDao newProxyInstance = (IUserDao) Proxy.newProxyInstance(loader, interfaces, invocationHandler); newProxyInstance.save(); ~~~