1、静态代理
/** 定义的代理接口 */
public interface Shopping {
Object[] doShopping(long money);
}
/** 代理类 */
public class ProxyShopping implements Shopping {
Shopping base;
ProxyShopping(Shopping base) {
this.base = base;
}
@Override
public Object[] doShopping(long money) {
//先做点其他事情
long readCost = (long) (money * 0.5);
System.out.println(String.format("花了%s块钱", readCost));
//这里才真正调用被代理对象的方法
Object[] things = base.doShopping(readCost);
//执行完后又可以做一些其他事情
if (things != null && things.length > 1) {
things[0] = "被掉包的东西!!";
}
return things;
}
}
2、动态代理
public class TestDynamic {
public static void testDynamicProxy() {
Shopping women = new ShoppingImpl();
//通过系统提供的api生成动态代理对象women,
women = (Shopping) Proxy.newProxyInstance(TestDynamic.class.getClassLoader(), women.getClass().getInterfaces(), new ShoppingHandler(women));
System.out.println(Arrays.toString(women.doShopping(100)));
}
}
/**
* 动态代理真正执行方法的地方
*/
public class ShoppingHandler implements InvocationHandler {
Object base;//被代理的原始对象
public ShoppingHandler(Object base) {
this.base = base;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if ("doShopping".equals(method.getName())) {//代理的其中一个接口
Long money = (Long) args[0];//先做的其他事情
long readCost = (long) (money * 0.5);
System.out.println(String.format("花了%s块钱", readCost));
Object[] things = (Object[]) method.invoke(base, readCost);//真正执行被代理对象的方法
if (things != null && things.length > 1) {//修改返回值
things[0] = "被掉包的东西!!";
}
return things;
}
if ("doSomething".equals(method.getName())) {//代理的另一个接口
return null;
}
if ("doSomethingElse".equals(method.getName())) {//代理的另一个接口
return null;
}
return null;
}
}
3、系统api生成动态代理做的事情
1)动态代理,实际上是根据传入的代理对象信息,动态生成一个新的代理类,
该代理类一个成员变量为 InvocationHandler
该代理类的构造器参数为InvocationHandler;
该代理类的方法为被代理的对象的接口方法;
该代理类的代理方法中,会调用 InvocationHandler.invoke(...),所以动态生成的代理对象,真正执行方法的地方在于InvocationHandler的实现类
newProxyInstance(ClassLoader, proxyInterfaces[],InvocationHandler);内部只是动态生成代理类。
public class Proxy implements java.io.Serializable {
public static Object newProxyInstance(
ClassLoader loader, //用来加载生成的代理类的类加载器
Class<?>[] interfaces, //被代理的对象的接口方法数组
InvocationHandler h) //代理类的方法中会调用h.invoke(...)
throws IllegalArgumentException {
Objects.requireNonNull(h);
final Class<?>[] intfs = interfaces.clone();
/* 根据被代理对象的接口生成代理类,该类的方法就是被代理对象的接口方法,并通过loader加载到虚拟机中
* 代理方法中会调用 InvocationHandler.invoke(...)
*/
Class<?> cl = getProxyClass0(loader, intfs);
try {
//给代理类创建一个构造器,参数为 InvocationHandler
final Constructor<?> cons = cl.getConstructor(constructorParams);
final InvocationHandler ih = h;//传入的InvocationHandler对象
if (!Modifier.isPublic(cl.getModifiers())) {
cons.setAccessible(true);
}
return cons.newInstance(new Object[]{h});//把InvocationHandler传入代理类构造器中
//返回的代理类,在调用被代理对象的接口方法时,真正调用的是InvocationHandler的invoke(...)
} catch (IllegalAccessException|InstantiationException e) {
throw new InternalError(e.toString(), e);
} catch (InvocationTargetException e) {
Throwable t = e.getCause();
if (t instanceof RuntimeException) {
throw (RuntimeException) t;
} else {
throw new InternalError(t.toString(), t);
}
} catch (NoSuchMethodException e) {
throw new InternalError(e.toString(), e);
}
}
}
总结:
动态代理跟静态代理,原理是一样的。只不过动态代理是动态生成代理类,不需要程序员手动编写代理类。