说动态代理之前,先来看一下静态代理的实现
//静态代理实例
public class StaticProxyTest {
public static void main(String[] args) {
ErkeClothFactory erkeClothFactory = new ErkeClothFactory();
ClothFactory proxyClothFactory = new ProxyClothFactory(erkeClothFactory);
proxyClothFactory.doCloth();
}
}
//接口
interface ClothFactory{
void doCloth();
}
//代理类
class ProxyClothFactory implements ClothFactory{
private ClothFactory factory;
public ProxyClothFactory(ClothFactory factory){
this.factory = factory;
}
@Override
public void doCloth() {
System.out.println("代理工厂做一些准备操作");
factory.doCloth();
System.out.println("代理工程做一些后续操作");
}
}
//被代理类
class ErkeClothFactory implements ClothFactory{
@Override
public void doCloth() {
System.out.println("Erke正在生产衣服");
}
}
动态代理
-
区别于静态代理
- 我们希望在编译过程中不写定代理类,在执行过程中通过反射技术来动态的生成代理类
-
需要解决的问题
- 如何动态的生成一个代理类的对象
- 创建一个类,定义一个方法,调用Proxy.newProxyInstance方法来生成代理类
- 在代理类中调用方法,被代理类怎么实现调用同名方法
- 创建一个类实现InvocationHandler接口,重写invoke方法
//动态代理举例 public class ProxyTest { public static void main(String[] args) { //1.创建被代理类 SuperMan superMan = new SuperMan(); //2.创建代理类 Human proxyClass = (Human) ProxyFactory.getProxyClass(superMan); //3.调用方法 String belief = proxyClass.belief(); System.out.println(belief); proxyClass.eat("炸鸡火腿汉堡包"); System.out.println("************************"); //为了展示动态性,我们调用一下静态代理的例子 ErkeClothFactory erkeClothFactory = new ErkeClothFactory(); ClothFactory clothFactory = (ClothFactory) ProxyFactory.getProxyClass(erkeClothFactory); clothFactory.doCloth(); } } //定义一个接口 interface Human{ String belief(); void eat(String food); } //被代理类 class SuperMan implements Human{ @Override public String belief() { return "I believe I can fly"; } @Override public void eat(String food) { System.out.println("我喜欢吃" + food); } } class ProxyFactory{ //调用此方法动态生成一个代理类,传入参数为被代理类 public static Object getProxyClass(Object obj){ MyInvocationHandler myInvocationHandler = new MyInvocationHandler(obj); return Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(),myInvocationHandler); } } class MyInvocationHandler implements InvocationHandler{ private Object obj; public MyInvocationHandler(Object obj){ this.obj = obj; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { Object invoke = method.invoke(obj, args); return invoke; } }
- 如何动态的生成一个代理类的对象