深入理解jdk动态代理—手动实现一个动态代理

最近在看《Spring5核心原理》,看到代理模式这一节,有一个手动实现动态代理,想要运行一下,理一下整个过程,但是网上找不到源码,于是自己手动敲了一个,在这里做个分享供大家学习和理解动态代理:

package porxy;
public class Customer implements Person{
	@Override
	public void findLove() {
		System.out.println("高富帅");
		System.out.println("有6块腹肌");
	}
}
package porxy;
import java.lang.reflect.Method;
public class GPMeipo implements GPInvocationHandler{
	
	private Object target;
	
	public Object getInstance(Object target) throws Exception{
		this.target = target;
		
		Class<?> clazz = target.getClass();
		return GPProxy.newProxyInstance(new GPClassLoader(), clazz.getInterfaces(), this);
	}
	
	@Override
	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
		before();
		method.invoke(this.target, args);
		after();
		
		return null;
	}
	
	private void before() {
		System.out.println("我是媒婆:我要给你找对象,现在已经确认你的需求");
		System.out.println("开始物色");
	}
	
	private void after() {
		System.out.println("如果合适,开始办事!");
	}
}
package porxy;
import java.io.File;
import java.io.FileWriter;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import javax.tools.JavaCompiler;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;

/**
 * 用来生成源代码的工具类
 */
public class GPProxy {

	public static final String ln = "\r\n";

	public static Object newProxyInstance(GPClassLoader classLoader, Class<?>[] interfaces, GPInvocationHandler h) {

		try {
		    //动态生成源代码文件.java文件
			String src = generateSrc(interfaces);
			
			//编译生成的.java文件
			String filePath = GPProxy.class.getResource("").getPath();
			File f = new File(filePath + "$Proxy0.java");
			FileWriter fw = new FileWriter(f);
			fw.write(src);
			fw.flush();
			fw.close();

			JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
			StandardJavaFileManager manager = compiler.getStandardFileManager(null, null, null);
			Iterable iterable = manager.getJavaFileObjects(f);

			JavaCompiler.CompilationTask task = compiler.getTask(null, manager, null, null, null, iterable);
			task.call();
			manager.close();
			
			//加载编译后的类
			Class proxyClass = classLoader.findClass("$Proxy0");
			Constructor c = proxyClass.getConstructor(GPInvocationHandler.class);
			f.delete();
			
			//返回字节码重组后生成的新的代理类
			return c.newInstance(h);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;
	}

	private static String generateSrc(Class<?>[] interfaces) {
		StringBuffer sb = new StringBuffer();
		sb.append("package porxy;" + ln);
		sb.append("import porxy.Person;" + ln);
		sb.append("import java.lang.reflect.*;" + ln);
		sb.append("public class $Proxy0 implements " + interfaces[0].getName() + "{" + ln);
		sb.append("GPInvocationHandler h;" + ln);
		sb.append("public $Proxy0(GPInvocationHandler h ){" + ln);
		sb.append("this.h = h;");
		sb.append("}" + ln);
		for (Method m : interfaces[0].getMethods()) {
			Class<?>[] params = m.getParameterTypes();

			StringBuffer paramNames = new StringBuffer();
			StringBuffer paramValues = new StringBuffer();
			StringBuffer paramClasses = new StringBuffer();

			for (int i = 0; i < params.length; i++) {
				Class clazz = params[i];
				String type = clazz.getName();
				String paramName = toLowerFirstCase(clazz.getSimpleName());
				paramNames.append(type + " " + paramName);
				paramValues.append(paramName);
				paramClasses.append(clazz.getName() + ".class");

				if (i > 0 && i < params.length - 1) {
					paramNames.append(",");
					paramClasses.append(",");
					paramValues.append(",");
				}
			}

			sb.append("public " + m.getReturnType().getName() + " " + m.getName() + "(" + paramNames.toString() + ") {"
					+ ln);
			sb.append("try{" + ln);
			sb.append("Method m = " + interfaces[0].getName() + ".class.getMethod(\"" + m.getName() + "\",new Class[]{"
					+ paramClasses.toString() + "});" + ln);
			sb.append((hasReturnValue(m.getReturnType()) ? "return " : "")
					+ getCaseCode("this.h.invoke(this,m,new Object[]{" + paramValues + "})", m.getReturnType()) + ";"
					+ ln);
			sb.append("}catch(Error _ex){}");
			sb.append("catch(Throwable e){" + ln);
			sb.append("throw new UndeclaredThrowableException(e);" + ln);
			sb.append("}");
			sb.append(getReturnEmptyCode(m.getReturnType()));
			sb.append("}");
		}
		sb.append("}" + ln);

		return sb.toString();
	}

	private static Map<Class, Class> mappings = new HashMap<Class, Class>();
	static {
		mappings.put(int.class, Integer.class);
	}

	private static String getReturnEmptyCode(Class<?> returnClass) {
		if (mappings.containsKey(returnClass)) {
			return "return 0;";
		} else if (returnClass == void.class) {
			return "";
		} else {
			return "retunr null;";
		}
	}

	private static String getCaseCode(String code, Class<?> returnClass) {
		if (mappings.containsKey(returnClass)) {
			return "((" + mappings.get(returnClass).getName() + ")" + code + ")." + returnClass.getSimpleName()
					+ "Value()";
		}
		return code;
	}

	private static boolean hasReturnValue(Class<?> clazz) {
		return clazz != void.class;
	}

	private static String toLowerFirstCase(String src) {
		char[] chars = src.toCharArray();
		chars[0] += 32;
		return String.valueOf(chars);
	}
}
package porxy;
import java.lang.reflect.Method;
public interface GPInvocationHandler {
	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable;
}
package porxy;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class GPClassLoader extends ClassLoader {
	private File classPathFile;
	public GPClassLoader() {
		String classPath = GPClassLoader.class.getResource("").getPath();
		this.classPathFile = new File(classPath);
	}
	@Override
	protected Class<?> findClass(String name) throws ClassNotFoundException {
		String className = GPClassLoader.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();
				} finally {
					if (null != in) {
						try {
							in.close();
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
					if (out != null) {
						try {
							out.close();
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
				}
			}
		}
		return null;
	}
}

顺便贴出动态生成的类,供大家参考:

package porxy;
import porxy.Person;
import java.lang.reflect.*;
public class $Proxy0 implements porxy.Person{
	
	GPInvocationHandler h;
	
	public $Proxy0(GPInvocationHandler h ){
		
		this.h = h;
	}
	public void findLove() {
		try{
			Method m = porxy.Person.class.getMethod("findLove",new Class[]{});
			this.h.invoke(this,m,new Object[]{});
		}catch(Error _ex){}catch(Throwable e){
			throw new UndeclaredThrowableException(e);
		}
	}
}

如果以上内容有任何问题,请联系我删除。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值