JDK动态代理实现原理以及手写实现JDK动态代理
JDK动态代理的过程
JDK动态代理采用字节重组,重新生成对象来替代原始对象,以达到动态代理的目的。
JDK中有一个规范,在ClassPath下只要是$开头的.class文件,一般都是自动生成的。
要实现JDK动态代理生成对象,首先得弄清楚JDK动态代理的过程。
1.获取被代理对象的引用,并且使用反射获取它的所有接口。
2.JDK动态代理类重新生成一个新的类,同时新的类要实现被代理类实现的所有接口。
3.动态生成Java代码,新添加的业务逻辑方法由一定的逻辑代码调用。
4.编译新生成的Java代码(.class文件)。
2.重新加载到VM中运行。
复制代码
手写实现JDK动态代理
JDK动态代理功能非常强大, 接下来就模仿JDK动态代理实现一个属于自己的动态代理。
创建MyInvocationHandler接口
参考JDK动态代理的 InvocationHandler
接口,创建属于自己的 MyInvocationHandler
接口
public interface MyInvocationHandler {
Object invoke(Object proxy, Method method, Object[] args) throws Throwable;
}
复制代码
创建MyClassLoader类加载器
public class MyClassLoader extends ClassLoader {
private File classPathFile;
public MyClassLoader() {
String classPath = MyClassLoader.class.getResource("").getPath();
this.classPathFile = new File(classPath);
}
@Override
protected Class<?> findClass(String name) {
String className = MyClassLoader.class.getPackage().getName() + "." + name;
if (classPathFile != null) {
File classFile = new File(classPathFile, name.replaceAll("\\.", "/") + ".class");
if (classFile.exists()) {
FileInputStream in = null;
ByteArrayOutputStream out = null;
try {
in = new FileInputStream(classFile);
out = new ByteArrayOutputStream();
byte[] buff = new byte[1024];
int len;
while ((len = in.read(buff)) != -1) {
out.write(buff, 0, len);
}
return defineClass(className, out.toByteArray(), 0, out.size());
} catch (Exception e) {
e.printStackTrace();
}
}
}
return null;
}
}
复制代码
创建代理类
创建的代理类是整个JDK动态代理的核心
public class MyProxy {
// 回车、换行符
public static final String ln = "\r\n";
/**
* 重新生成一个新的类,并实现被代理类实现的所有接口
*
* @param classLoader 类加载器
还没有评论,来说两句吧...