-
动态代理的概念:相对于静态代理,动态代理可以一次性代理多个服务,而且JDK实现的动态代理只能代理接口。
动态代理用到的类: Proxy
Proxy的使用方法:
public class ProxyClass { public static void main(String[] args) { Tom tom = new Tom(); //创建动态代理 final Object proxyInstance = Proxy.newProxyInstance(ProxyClass.class.getClassLoader(), new Class[]{IMassage.class, IWash.class}, new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("Hello 动态代理"); return null; } }); IMassage iMassage = (IMassage) proxyInstance; iMassage.massage(); } }
-
动态代理的使用讲解:
proxyInstance对象代理了IMassage和IWash两个抽象的接口,所以可以通过proxyInstance对象获取IMassage和IWash对象。//通过强转的方式就可以获取IMassage对象,然后调用massage方法。 IMassage iMassage = (IMassage) proxyInstance; iMassage.massage();
-
InvocationHandler的作用
public interface InvocationHandler { public Object invoke(Object proxy, Method method, Object[] args) throws Throwable; }
通过以上代码可以看出其实InvocationHandler是一个接口,作用就是当我们通过代理对象调用代理方法时,InvocationHandler就会监听到此方法,然后把调用的方法传进invoke方法。所以代码部分的打印语句就会输出结果了。
-
运行结果:
-
代理真正的实体类
通过反射的方式获取代理类对象,然后执行代理类的方法。以下是代码部分:public class ProxyClass { public static void main(String[] args) { final Tom tom = new Tom(); //创建动态代理 final Object proxyInstance = Proxy.newProxyInstance(ProxyClass.class.getClassLoader(), new Class[]{IMassage.class, IWash.class}, new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { // 只需要在return的时候通过invoke方法,把实体类对象传进来就可以了 return method.invoke(tom, args); } }); IMassage iMassage = (IMassage) proxyInstance; iMassage.massage(); } }
-
运行结果:
动态代理的使用
于 2022-03-31 18:53:24 首次发布