-
Proxy :专门完成代理的操作类,是所有动态代理类的父类。通过此类为一 个或多个接口动态地生成实现类。
-
提供用于创建动态代理类和动态代理对象的静态方法
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-kS29WBvV-1652275886273)(C:UsersThinkAppDataRoamingTyporatypora-user-images1652274619957.png)]
-
如何根据加载到内存中的被代理类,动态创建一个代理类及其对象
class ProxyFactory{ public static Object getProxyInstance(Object obj) { MyInvacationHandler myInvacationHandler = new MyInvacationHandler(); myInvacationHandler.bind(obj); return Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(),myInvacationHandler); } } -
当通过代理类的对象调用方法时,如何动态去调用被代理类中对应的同名方法
class MyInvacationHandler implements InvocationHandler{ private Object obj; public void bind(Object obj) { this.obj = obj; } HumanUtil humanUtil = new HumanUtil(); @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { humanUtil.method1(); Object invokeValue = method.invoke(obj, args); humanUtil.method2(); return invokeValue; } } -
动态代理案例完整代码
interface Human{ String getBelif(); void eat(String food); } class HumanUtil{ public void method1(){ System.out.println("通用方法1"); } public void method2(){ System.out.println("通用方法2"); } } class SuperMan implements Human{ @Override public String getBelif() { return "I CAN FLY!!!"; } @Override public void eat(String food) { System.out.println("李狗喜欢吃"+food); } } class ProxyFactory{ public static Object getProxyInstance(Object obj) { MyInvacationHandler myInvacationHandler = new MyInvacationHandler(); myInvacationHandler.bind(obj); return Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(),myInvacationHandler); } } class MyInvacationHandler implements InvocationHandler{ private Object obj; public void bind(Object obj) { this.obj = obj; } HumanUtil humanUtil = new HumanUtil(); @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { humanUtil.method1(); Object invokeValue = method.invoke(obj, args); humanUtil.method2(); return invokeValue; } } public class ProxyTest { public static void main(String[] args) { SuperMan superMan = new SuperMan(); //代理类的对象 Human proxyInstance = (Human)ProxyFactory.getProxyInstance(superMan); //代理类调用方法时,会自动调用被代理类中的同名方法 proxyInstance.eat("11111111"); NikeClothFactory nikeClothFactory = new NikeClothFactory(); ClothFactory proxyNikeClothFactory = (ClothFactory)ProxyFactory.getProxyInstance(nikeClothFactory); proxyNikeClothFactory.produceCloth(); } }得到的结果如下图:
**总结:**通过代理类创建的代理对象进行方法的调用,实际是调用的被代理对象的方法(动态调用),通用方法直接写死。



