jdk动态代理代码实现
1、jdk动态代理代码实现
1、接口
public interface IUserService {void save();void delete();}
2、接口实现
@Service
public class UserServiceImpl implements IUserService {@Overridepublic void save() {System.out.println("UserServiceImpl.save");}@Overridepublic void delete() {System.out.println("UserServiceImpl.delete");}
}
3、代理类创建
@Test
public void testJdkProxy(){//使用jdk动态代理生成 代理对象IUserService userServiceProxy = (IUserService) Proxy.newProxyInstance(this.getClass().getClassLoader(), //类加载器userService.getClass().getInterfaces(), //给接口proxy 才可以生产代理new InvocationHandler() { //代理对象执行的接口//代理对象 反射执行的方法@Overridepublic Object invoke(Object proxy, Method method, Object[] args) throws Throwable {//这里进行增强System.out.println("log 日志输出" + method.getName());//真实对象执行 delete、save的方法Object obj = method.invoke(userService,args);return obj;}});System.out.println("userServiceProxy = " + userServiceProxy);userServiceProxy.save();userServiceProxy.delete();
}
4、原理
1、使用工具类生产代理对象 字节码
public class ProxyUtils{public static void main(String[] args) throws Exception {saveProxyFile();}private static void saveProxyFile() throws IOException {IUserService userService = new UserServiceImpl();FileOutputStream out = null;File file = new File("C:\\test\\" + "$Proxy0.class");file.createNewFile();try {byte[] classFile = ProxyGenerator.generateProxyClass("$Proxy0",userService.getClass().getInterfaces());out = new FileOutputStream(file);out.write(classFile);} catch (Exception e) {e.printStackTrace();} finally {try {if (out != null) {out.flush();out.close();}} catch (IOException e) {e.printStackTrace();}}}
}
2、源码分析