当前位置:首页 > CN2资讯 > 正文内容

Proxy代理类分析

13小时前CN2资讯

动态代理样例:

IGamePlayer gamePlayer = new GamePlayer("张三"); InvocationHandler handler=new GamePlayIH(gamePlayer); ClassLoader cl=gamePlayer.getClass().getClassLoader(); //该方法必须有classLoader、getInterfaces、InvocationHandler IGamePlayer proxy=(IGamePlayer) Proxy.newProxyInstance(cl, gamePlayer.getClass().getInterfaces(), handler); proxy.login("yinyueml", "sssss"); proxy.killBoss(); proxy.upgrade(); //具体实现InvocationHandler public class GamePlayIH implements InvocationHandler { Class cls = null; Object obj = null; public GamePlayIH(Object obj) { this.obj = obj; }         @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { //先调用类的方法 Object result=method.invoke(this.obj, args); //根据运行的方法做出操作。 if(method.getName().equalsIgnoreCase("login")){ System.out.println("有人再用我的账号登陆"); } return result; } }

运行结果为:

登陆用户名:yinyueml;玩家:张三上线 有人再用我的账号登陆

如果

//根据运行的方法做出操作。 if(method.getName().equalsIgnoreCase("login")){ System.out.println("有人再用我的账号登陆"); } Object result=method.invoke(this.obj, args);

运行结果为:

有人再用我的账号登陆 登陆用户名:yinyueml;玩家:张三上线



方法 newProxyInstance

 @CallerSensitive //详细分析这个注解     public static Object newProxyInstance(ClassLoader loader,                                           Class<?>[] interfaces,                                           InvocationHandler h)         throws IllegalArgumentException     {     //判断h是否为空         Objects.requireNonNull(h);         final Class<?>[] intfs = interfaces.clone();         final SecurityManager sm = System.getSecurityManager();         if (sm != null) {             checkProxyAccess(Reflection.getCallerClass(), loader, intfs);         }         /*          * Look up or generate the designated proxy class.          */          //该方法会返回一个动态代理类$Proxy0。即如果原先有相同的代理类,则直接用原来的,如果没有则新生成。需要提取,代码如下         Class<?> cl = getProxyClass0(loader, intfs);         /*          * Invoke its constructor with the designated invocation handler.          */         try {             if (sm != null) {                 checkNewProxyPermission(Reflection.getCallerClass(), cl);             }             final Constructor<?> cons = cl.getConstructor(constructorParams);             final InvocationHandler ih = h;             if (!Modifier.isPublic(cl.getModifiers())) {                 AccessController.doPrivileged(new PrivilegedAction<Void>() {                     public Void run() {                         cons.setAccessible(true);                         return null;                     }                 });             }             //加载器初始化h             return cons.newInstance(new Object[]{h});         } 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);         }     }

$Proxy0源代码

package com.sun.proxy; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.lang.reflect.UndeclaredThrowableException; import proxyPattern.IGamePlayer; //$Proxy()继承Proxy,将InvocationHandler通过构造方法的方式调用,并且在方法中进行调用invoke public final class $Proxy0 extends Proxy   implements IGamePlayer {   private static Method m1;   private static Method m2;   private static Method m5;   private static Method m4;   private static Method m3;   private static Method m0;   public $Proxy0(InvocationHandler paramInvocationHandler)     throws    {     super(paramInvocationHandler);   }   public final boolean equals(Object paramObject)     throws    {     try     {       return ((Boolean)this.h.invoke(this, m1, new Object[] { paramObject })).booleanValue();     }     catch (RuntimeException localRuntimeException)     {       throw localRuntimeException;     }     catch (Throwable localThrowable)     {     }     throw new UndeclaredThrowableException(localThrowable);   }   public final String toString()     throws    {     try     {       return (String)this.h.invoke(this, m2, null);     }     catch (RuntimeException localRuntimeException)     {       throw localRuntimeException;     }     catch (Throwable localThrowable)     {     }     throw new UndeclaredThrowableException(localThrowable);   } //该处upgrade调用invoke   public final void upgrade()     throws    {     try     {       this.h.invoke(this, m5, null);       return;     }     catch (RuntimeException localRuntimeException)     {       throw localRuntimeException;     }     catch (Throwable localThrowable)     {     }     throw new UndeclaredThrowableException(localThrowable);   } //该处killBoss调用invoke   public final void killBoss()     throws    {     try     {       this.h.invoke(this, m4, null);       return;     }     catch (RuntimeException localRuntimeException)     {       throw localRuntimeException;     }     catch (Throwable localThrowable)     {     }     throw new UndeclaredThrowableException(localThrowable);   } //该处login调用invoke   public final void login(String paramString1, String paramString2)     throws    {     try     {     //此处m3代表的为login方法,getName为login       this.h.invoke(this, m3, new Object[] { paramString1, paramString2 });       return;     }     catch (RuntimeException localRuntimeException)     {       throw localRuntimeException;     }     catch (Throwable localThrowable)     {     }     throw new UndeclaredThrowableException(localThrowable);   }   public final int hashCode()     throws    {     try     {       return ((Integer)this.h.invoke(this, m0, null)).intValue();     }     catch (RuntimeException localRuntimeException)     {       throw localRuntimeException;     }     catch (Throwable localThrowable)     {     }     throw new UndeclaredThrowableException(localThrowable);   }   static   {     try     {       m1 = Class.forName("java.lang.Object").getMethod("equals", new Class[] { Class.forName("java.lang.Object") });       m2 = Class.forName("java.lang.Object").getMethod("toString", new Class[0]);       m5 = Class.forName("proxyPattern.IGamePlayer").getMethod("upgrade", new Class[0]);       m4 = Class.forName("proxyPattern.IGamePlayer").getMethod("killBoss", new Class[0]);       m3 = Class.forName("proxyPattern.IGamePlayer").getMethod("login", new Class[] { Class.forName("java.lang.String"), Class.forName("java.lang.String") });       m0 = Class.forName("java.lang.Object").getMethod("hashCode", new Class[0]);       return;     }     catch (NoSuchMethodException localNoSuchMethodException)     {       throw new NoSuchMethodError(localNoSuchMethodException.getMessage());     }     catch (ClassNotFoundException localClassNotFoundException)     {     }     throw new NoClassDefFoundError(localClassNotFoundException.getMessage());   } }


    你可能想看:

    扫描二维码推送至手机访问。

    版权声明:本文由皇冠云发布,如需转载请注明出处。

    本文链接:https://www.idchg.com/info/24866.html

    分享给朋友:

    “Proxy代理类分析” 的相关文章

    使用newcom598优惠码注册域名,享受超值价格

    什么是newcom598优惠码? 我想和大家分享一个超值的优惠信息,那就是newcom598优惠码。这是一个专为Namecheap的新用户设计的优惠码,意在帮助刚开始建立自己在线业务的人以超优惠的价格注册.COM域名。通过这个优惠码,新用户可以以仅$5.98的价格获得首年的.COM域名,这样算下来在...

    eno VPS:掌握网络接口命名规则与性能优化技巧

    在了解eno VPS之前,我们先来看看什么是eno命名规则。ena作为一种网络接口命名方式,通过特定的规则来表示Linux系统中的网络设备。这种规则帮助用户更容易地识别和管理各种网络接口。具体来说,eno采用的是eno[n|d]的格式,主要用于板载设备。而对于热插拔设备,则使用ens[f][n|d]...

    如何使用RackNerd优惠码进行主机购买:节省开支的最佳策略

    RackNerd是一家成立于2017年的国外主机公司,作为一家新生力量,它迅速在市场上占据了一席之地。它的使命是为全球用户提供可靠且高性能的主机服务,帮助他们搭建自己的网络基础设施。我最喜欢RackNerd的地方是他们始终如一地致力于客户体验,这让我在使用他们的服务时非常安心。 RackNerd的服...

    台湾VPS:高效、稳定且安全的虚拟专用服务器解决方案

    台湾VPS,即虚拟专用服务器,是一种通过虚拟化技术将物理服务器划分为多个独立服务器的解决方案。这种服务不仅为用户提供独享的资源和灵活的管理权限,还能够提升性能和效率。在我使用台湾VPS的过程中,它让我深刻体会到这一技术的便利与强大。 台湾VPS的独特之处在于其地理位置和网络基础设施。位于东亚的台湾,...

    全面解读SFTP教程:安全文件传输的最佳实践

    什么是SFTP? 在计算机网络世界里,SFTP(Secure File Transfer Protocol)是一种安全的文件传输协议。它的主要用途是通过安全的方式在网络中传输数据。与传统的FTP(File Transfer Protocol)相比,SFTP引入了数据加密机制,这样一来,用户在传输文件...

    WordPress reCAPTCHA插件:提升网站安全与用户体验的最佳解决方案

    reCAPTCHA插件概述 在今天的网络环境中,安全性愈发重要,尤其是对于使用WordPress的网站。WordPress reCAPTCHA插件成为了一种流行的解决方案,它借助Google强大的reCAPTCHA服务,帮助我们有效地区分真实用户和可能扰乱网站的机器程序。在我接触这个插件之后,发现它...