ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的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(); ~~~