暂时没有时间做详细介绍了。
动态代理代码:
public class ProxyCopy {
public static Object newInstance(ClassLoader classLoader, Class<?>[] interfaces, InvocationHandler h) throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
ProxyCopyFactory proxyCopyFactory = new ProxyCopyFactory();
Class<?> proxyClass = proxyCopyFactory.apply(Robot.class.getClassLoader(), Robot.class.getInterfaces());
Constructor<?> constructor = proxyClass.getConstructor(InvocationHandler.class);
return constructor.newInstance(h);
}
public static class ProxyCopyFactory extends ClassLoader implements BiFunction<ClassLoader, Class<?>[], Class<?>> {
@Override
public Class<?> apply(ClassLoader classLoader, Class<?>[] classes) {
String className = classes[0].getSimpleName() + "Proxy";
//建立一个代理的class文件
byte[] bytes = ProxyGenerator.generateProxyClass(className, classes);
return defineClass0(classLoader, className, bytes, 0, bytes.length);
}
private Class<?> defineClass0(ClassLoader loader, String name, byte[] b, int off, int len) {
return defineClass(name, b, off, len);
}
}
}
调用:
@Test
public void test1() throws ClassNotFoundException, IOException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
IRobot iRobot = (IRobot) ProxyCopy.newInstance(Robot.class.getClassLoader(), Robot.class.getInterfaces(), new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("前");
Object invoke = method.invoke(new Robot());
System.out.println("后");
return invoke;
}
});
iRobot.say();
}
结果:
前
Robot Say sth...
后