当前位置: 移动技术网 > IT编程>开发语言>Java > java 自定义类加载器

java 自定义类加载器

2020年04月15日  | 移动技术网IT编程  | 我要评论

csi拉斯维加斯第14季,rstray,小林初花

 按照网上的惯例,先给出静态代理到动态代理的例子吧;要不然后面的理论和源码分析没有铺垫,大家都有点迷糊。

静态代理:

/**
 * 声音接口,用于代理接口
 */
public interface ivoice {

    void song();
}

 

/**
 * 歌手类
 */
public class singer implements ivoice{

    public void song(){
        system.out.println("歌手在唱歌...");
    }
}

 

/**
 * 代理类:喇叭(英语单词太难了,怕你们不认识,直接用拼音了)
 */
public class laba implements ivoice{

    private ivoice voice;

    public laba(ivoice voice) {
        this.voice = voice;
    }

    public void song() {
        system.out.println("歌手的声音被我放大了");
        this.voice.song();
        system.out.println("歌手停止说话了");
    }
}

执行类:

public class main {
    public static void main(string[] args) {
        singer singer=new singer();
        ivoice voice=new laba(singer);
        voice.song();
    }
}

打印结果:

 

上面的接口似乎没有什么作用,如果我们把接口去掉呢?

/**
 * 歌手类
 */
public class singer {
    public void song(){
        system.out.println("歌手在唱歌...");
    }
}

 

/**
 * 代理类:喇叭(英语单词太难了,怕你们不认识,直接用拼音了)
 */
public class laba {
    private singer singer;

    public laba(singer singer) {
        this.singer = singer;
    }
    public void  song(){
        system.out.println("歌手的声音被我放大了");
        this.singer.song();
        system.out.println("歌手停止说话了");
    }
}

 

public class main {
    public static void main(string[] args) {
        singer singer=new singer();
        laba laba=new laba(singer);
        laba.song();
    }
}

打印的结果和上面的一模一样,那么没有了接口的代理还算不算代理呢

或者干脆我连代理的方法名字song()都和singer类中的song()方法名不一样。

这样子:

/**
 * 歌手类
 */
public class singer {
    public void song(){
        system.out.println("歌手在唱歌...");
    }
}

/**
 * 代理类:喇叭(英语单词太难了,怕你们不认识,直接用拼音了)
 */
public class laba {
    private singer singer;

    public laba(singer singer) {
        this.singer = singer;
    }
    public void  labasong(){
        system.out.println("歌手的声音被我放大了");
        this.singer.song();
        system.out.println("歌手停止说话了");
    }
}


public class main {
    public static void main(string[] args) {
        singer singer=new singer();
        laba laba=new laba(singer);
        laba.labasong();
    }
}

这种没有接口,代理类和实际执行类的方法都不一样了,还算不算代理呢?

找找度娘吧:

 

定义里面并没有规定使用接口和代理方法名一样才叫代理。所以只要实现了一个对象对另一个对象的访问以及方法调用就是代理模式,现在看来我们在代码中随随便便一个对象方法的调用都是一个模式的使用了。

还是回到大家都认可的有接口的静态代理上来吧;

从那个静态代理的例子里面能看出来,

我们实实在在的创建了一个代理类laba.java,并且编辑器编译成class字节码文件,然后被虚拟机导入,进行校验,分析

最终在内存里面创建出一个对象,让他实现了代理功能,供我们使用;

这种模式在被代理的方法确定的情况下,是能满足需求的;反之,则无法使用静态代理模式了。

相对于静态代理就是动态代理了。

动态代理模式就是用程序来创建代理对象的模式。

jdk动态代理模式:

 按照惯例先上代码,熟悉基本用法吧。

/**
 * 声音接口,用于代理接口
 */
public interface ivoice {
    object song();
}
/**
 * 歌手类
 */
public class singer implements ivoice{
    public object song(){
        system.out.println("歌手在唱歌...");
        return null;
    }
}
import java.lang.reflect.invocationhandler;
import java.lang.reflect.method;

//方法委托类
public class methodhandler implements invocationhandler {

    //原对象
    private object orgobject;

    public methodhandler(object orgobject) {
        this.orgobject = orgobject;
    }

    public object invoke(object proxy, method method, object[] args) throws throwable {
        system.out.println("歌手的声音被我放大了");
        //res是被代理方法的返回值
        object res=method.invoke(orgobject,args);
        system.out.println("歌手停止说话了");
        return res;
    }
}
import java.lang.reflect.proxy;

//执行类
public class main {
    public static void main(string[] args) {
        singer singer=new singer();
        methodhandler methodhandler=new methodhandler(singer);
        ivoice proxy=(ivoice) proxy.newproxyinstance(singer.getclass().getclassloader(), singer.getclass().getinterfaces(), methodhandler);
        proxy.song();
    }
}

打印结果:

 

 我们一般是在idea或者eclipse上面开发java项目,编辑器帮我们做好了编译工作或者说帮我们编译成了class文件,然后可以直接执行;

也就是说编辑器帮我们做好了javac(编译成class文件)和java(执行java程序)命令的工作。

那么jdk代理是

首先创建了类,然后自己编译成class文件,载入到虚拟机里面,创建类对象

还是直接创建了class文件,载入到虚拟机里面,创建类对象,

还是有利用黑科技直接跳过虚拟机的检测和分析,直接在虚拟机里面搞出来一个对象。

 

这个我们要从源码去入手了。

首先来看   proxy.newproxyinstance ()这个方法

@callersensitive
    public static object newproxyinstance(classloader loader,
                                          class<?>[] interfaces,
                                          invocationhandler h)
        throws illegalargumentexception
    {
        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.
         */
        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;
                    }
                });
            }
            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);
        }
    }

删除多余的代码,并添加一些注释

public static object newproxyinstance(classloader loader,class<?>[] interfaces,invocationhandler h) throws illegalargumentexception{      

        final class<?>[] intfs = interfaces.clone();     
        //获得代理类对象
        class<?> cl = getproxyclass0(loader, intfs);  
   
         //代理类对象的构造器函数
            final constructor<?> cons = cl.getconstructor(constructorparams);
            final invocationhandler ih = h;
            //实例化一个对象
            return cons.newinstance(new object[]{h});
        } 
    }                

继续查看  getproxyclass0()方法

private static class<?> getproxyclass0(classloader loader,
                                           class<?>... interfaces) {
        if (interfaces.length > 65535) {
            throw new illegalargumentexception("interface limit exceeded");
        }

        // if the proxy class defined by the given loader implementing
        // the given interfaces exists, this will simply return the cached copy;
        // otherwise, it will create the proxy class via the proxyclassfactory
        //缓存里面有就直接取,没有的话就通过proxyclassfactory类创建
        return proxyclasscache.get(loader, interfaces);
    }    

 

这里直接从cache里面取出来的,有get就一定有添加的方法;在看一下上面的注释;我们目前不知道proxclassfactory类在哪里,也不知道是怎么创建的。

还是老老实实的追到   proxyclasscache.get(loader, interfaces);方法里面去;

 1 public v get(k key, p parameter) {
 2         objects.requirenonnull(parameter);
 3 
 4         expungestaleentries();
 5 
 6         object cachekey = cachekey.valueof(key, refqueue);
 7 
 8         // lazily install the 2nd level valuesmap for the particular cachekey
 9         concurrentmap<object, supplier<v>> valuesmap = map.get(cachekey);
10         if (valuesmap == null) {
11             concurrentmap<object, supplier<v>> oldvaluesmap
12                 = map.putifabsent(cachekey,
13                                   valuesmap = new concurrenthashmap<>());
14             if (oldvaluesmap != null) {
15                 valuesmap = oldvaluesmap;
16             }
17         }
18 
19         // create subkey and retrieve the possible supplier<v> stored by that
20         // subkey from valuesmap
21         object subkey = objects.requirenonnull(subkeyfactory.apply(key, parameter));
22         supplier<v> supplier = valuesmap.get(subkey);
23         factory factory = null;
24 
25         while (true) {
26             if (supplier != null) {
27                 // supplier might be a factory or a cachevalue<v> instance
28                 v value = supplier.get();
29                 if (value != null) {
30                     return value;
31                 }
32             }
33             // else no supplier in cache
34             // or a supplier that returned null (could be a cleared cachevalue
35             // or a factory that wasn't successful in installing the cachevalue)
36 
37             // lazily construct a factory
38             if (factory == null) {
39                 factory = new factory(key, parameter, subkey, valuesmap);
40             }
41 
42             if (supplier == null) {
43                 supplier = valuesmap.putifabsent(subkey, factory);
44                 if (supplier == null) {
45                     // successfully installed factory
46                     supplier = factory;
47                 }
48                 // else retry with winning supplier
49             } else {
50                 if (valuesmap.replace(subkey, supplier, factory)) {
51                     // successfully replaced
52                     // cleared cacheentry / unsuccessful factory
53                     // with our factory
54                     supplier = factory;
55                 } else {
56                     // retry with current supplier
57                     supplier = valuesmap.get(subkey);
58                 }
59             }
60         }
61     }

代码比较长,先从30行return处开始向上分析,去除多余代码,代码如下:

 1 public v get(k key, p parameter) {        
 2         object subkey = objects.requirenonnull(subkeyfactory.apply(key, parameter));
 3         supplier<v> supplier = valuesmap.get(subkey);
 4         factory factory = null;
 5 
 6         while (true) {
 7             if (supplier != null) {               
 8                 v value = supplier.get();
 9                 if (value != null) {
10                     return value;
11                 }
12             }        
13         }
14     }

value来自  supplier ; supplier 来自valuesmap.get(subkey);那么由此推断subkey是代理类对象的key值,

那么  subkeyfactory.apply(key, parameter)就一定是创建代理类对象的方法,并且添加到缓存中去的。

查看  subkeyfactory.apply(key, parameter)源码:

   

找到了之前提到了proxyclassfactory类。确认无疑了,就是在这里创建的代理类对象

apply()源码

源码经过删减,并且添加了中文注释。

 1 public class<?> apply(classloader loader, class<?>[] interfaces) {
 2             map<class<?>, boolean> interfaceset = new identityhashmap<>(interfaces.length);
 3             //我们目前只有一个接口,所以不用考虑循环问题
 4             for (class<?> intf : interfaces) {
 5               
 6                 class<?> interfaceclass = null;
 7                 try {
 8                     //获取接口类对象
 9                     interfaceclass = class.forname(intf.getname(), false, loader);
10                 }            
11                 /*
12                  * verify that the class object actually represents an
13                  * interface.
14                      判断传过来的类对象参数是否是接口
15                  */
16                 if (!interfaceclass.isinterface()) {
17                     throw new illegalargumentexception(
18                         interfaceclass.getname() + " is not an interface");
19                 }               
20             }
21 
22             string proxypkg = null;     // package to define proxy class in
23             int accessflags = modifier.public | modifier.final;
24 
25            
26 
27             if (proxypkg == null) {
28                 // if no non-public proxy interfaces, use com.sun.proxy package
29                 //如果为空,使用com.sun.proxy package作为代理对象的包名
30                 proxypkg = reflectutil.proxy_package + ".";
31             }
32 
33             /*
34              * choose a name for the proxy class to generate.
35                nextuniquenumber是一个atomiclong值,线程安全的原子操作,先获取当前值,在把内部的long值+1
36              */
37             long num = nextuniquenumber.getandincrement();
38             // private static final string proxyclassnameprefix = "$proxy";
39             //最终路径大概这样:com.sun.proxy package.$proxy0
40             string proxyname = proxypkg + proxyclassnameprefix + num;
41 
42             /*
43              * generate the specified proxy class.
44                  创建一个指定的代理类
45              */
46             byte[] proxyclassfile = proxygenerator.generateproxyclass(
47                 proxyname, interfaces, accessflags);
48             try {
49                 return defineclass0(loader, proxyname,
50                                     proxyclassfile, 0, proxyclassfile.length);
51             }
52         }
53     }

 

大概可以推断出46行生成了字节数组,defineclass0()将字节数组实例化成了一个对象并返回上级方法,然后返回给我们;这里先把defineclass0()放一放,先看看

proxygenerator.generateproxyclass()是如何产生字节数组的

追进去看看。

 1 public static byte[] generateproxyclass(final string var0, class<?>[] var1, int var2) {
 2         proxygenerator var3 = new proxygenerator(var0, var1, var2);        
 3         final byte[] var4 = var3.generateclassfile();
 4         //private static final boolean savegeneratedfiles = (boolean)accesscontroller.doprivileged(new getbooleanaction("sun.misc.proxygenerator.savegeneratedfiles"));
 5         //保存产生的文件
 6         if (savegeneratedfiles) {
 7             accesscontroller.doprivileged(new privilegedaction<void>() {
 8                 public void run() {
 9                     try {
10                         int var1 = var0.lastindexof(46);
11                         path var2;
12                         if (var1 > 0) {
13                             path var3 = paths.get(var0.substring(0, var1).replace('.', file.separatorchar));
14                             files.createdirectories(var3);
15                             var2 = var3.resolve(var0.substring(var1 + 1, var0.length()) + ".class");
16                         } else {
17                             var2 = paths.get(var0 + ".class");
18                         }
19 
20                         files.write(var2, var4, new openoption[0]);
21                         return null;
22                     } catch (ioexception var4x) {
23                         throw new internalerror("i/o exception saving generated file: " + var4x);
24                     }
25                 }
26             });
27         }
28 
29         return var4;
30     }

从27行 return往分析;第六行  savegeneratedfiles  判断是否保存生成的文件,可以推断出var4就是最终完整的字节数组。

这个地方记住第4行中的路径  sun.misc.proxygenerator.savegeneratedfiles。后面我们需要用这个路径把字节码文件输出到本地来。

既然是第三行生成的字节数组,那么我们就追进去看看内容吧

generateclassfile()
删除了部分代码,可以大概看到var14向var13里面写了很多字节数据;
 private byte[] generateclassfile() {
         //添加hashcode方法
        this.addproxymethod(hashcodemethod, object.class);
        //添加equals方法
        this.addproxymethod(equalsmethod, object.class);
        //添加tostring方法
        this.addproxymethod(tostringmethod, object.class);
        class[] var1 = this.interfaces;
        int var2 = var1.length;      
        //方法和字段都不能超过65535个,不过我们在自定义类的时候一般不会超过这个数
        if (this.methods.size() > 65535) {
            throw new illegalargumentexception("method limit exceeded");
        } else if (this.fields.size() > 65535) {
            throw new illegalargumentexception("field limit exceeded");
        } else {
          
            bytearrayoutputstream var13 = new bytearrayoutputstream();
            dataoutputstream var14 = new dataoutputstream(var13);

            try {
                var14.writeint(-889275714);
                var14.writeshort(0);
                var14.writeshort(49);
                this.cp.write(var14);
                var14.writeshort(this.accessflags);
                var14.writeshort(this.cp.getclass(dottoslash(this.classname)));
                var14.writeshort(this.cp.getclass("java/lang/reflect/proxy"));
                var14.writeshort(this.interfaces.length);
                class[] var17 = this.interfaces;
                int var18 = var17.length;

                for(int var19 = 0; var19 < var18; ++var19) {
                    class var22 = var17[var19];
                    var14.writeshort(this.cp.getclass(dottoslash(var22.getname())));
                }

                var14.writeshort(this.fields.size());
                var15 = this.fields.iterator();

                while(var15.hasnext()) {
                    proxygenerator.fieldinfo var20 = (proxygenerator.fieldinfo)var15.next();
                    var20.write(var14);
                }

                var14.writeshort(this.methods.size());
                var15 = this.methods.iterator();

                while(var15.hasnext()) {
                    proxygenerator.methodinfo var21 = (proxygenerator.methodinfo)var15.next();
                    var21.write(var14);
                }

                var14.writeshort(0);
                return var13.tobytearray();
            } 
        }
    }

现在回到defineclass0()方法。

 

 

这是一个native方法,直接调用虚拟机的方法了;完了,看不到怎么实现的了。我猜测defineclass0()调用的是类加载器里面的方法。

如果对类加载器不熟悉的,可以看看这篇文章:java 自定义类加载器  ,你会发现我们自定义的类加载器也是将class文件读取成字节数组交给虚拟机的。

 

总结:

jdk动态代理的代理对象来自一个字节数组;

这个数组存放的是已经编译过后的内容;

并且将字节数组交给虚拟机进行实例化。

 
上面说到可以将字节码写入到本地文件中。现在来实现这个功能。
//执行类
public class main {
    public static void main(string[] args) {
        system.getproperties().put("sun.misc.proxygenerator.savegeneratedfiles","true");
        singer singer=new singer();
        methodhandler methodhandler=new methodhandler(singer);
        ivoice proxy=(ivoice) proxy.newproxyinstance(singer.getclass().getclassloader(), singer.getclass().getinterfaces(), methodhandler);
        proxy.song();
    }
}

我这边使用idea运行的,到项目的根目录下看看。

 

 

 和我们平时看到的class文件差不多,反正也不怎么能看明白。

 利用jd-gui对代码进行反编译: 

package com.sun.proxy;

import f.d.ivoice;
import java.lang.reflect.invocationhandler;
import java.lang.reflect.method;
import java.lang.reflect.proxy;
import java.lang.reflect.undeclaredthrowableexception;

public final class $proxy0 extends proxy implements ivoice {
  private static method m1;
  
  private static method m2;
  
  private static method m3;
  
  private static method m0;
  
  public $proxy0(invocationhandler paraminvocationhandler) {
    super(paraminvocationhandler);
  }
  
  public final boolean equals(object paramobject) {
    try {
      return ((boolean)this.h.invoke(this, m1, new object[] { paramobject })).booleanvalue();
    } catch (error|runtimeexception error) {
      throw null;
    } catch (throwable throwable) {
      throw new undeclaredthrowableexception(throwable);
    } 
  }
  
  public final string tostring() {
    try {
      return (string)this.h.invoke(this, m2, null);
    } catch (error|runtimeexception error) {
      throw null;
    } catch (throwable throwable) {
      throw new undeclaredthrowableexception(throwable);
    } 
  }
  
  public final object song() {
    try {
      return this.h.invoke(this, m3, null);
    } catch (error|runtimeexception error) {
      throw null;
    } catch (throwable throwable) {
      throw new undeclaredthrowableexception(throwable);
    } 
  }
  
  public final int hashcode() {
    try {
      return ((integer)this.h.invoke(this, m0, null)).intvalue();
    } catch (error|runtimeexception error) {
      throw null;
    } catch (throwable throwable) {
      throw new undeclaredthrowableexception(throwable);
    } 
  }
  
  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]);
      m3 = class.forname("f.d.ivoice").getmethod("song", new class[0]);
      m0 = class.forname("java.lang.object").getmethod("hashcode", new class[0]);
      return;
    } catch (nosuchmethodexception nosuchmethodexception) {
      throw new nosuchmethoderror(nosuchmethodexception.getmessage());
    } catch (classnotfoundexception classnotfoundexception) {
      throw new noclassdeffounderror(classnotfoundexception.getmessage());
    } 
  }
}

jdk动态代理就说到这了,后面继续说cglib动态代理。

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网