资讯专栏INFORMATION COLUMN

自定义类加载器

clasnake / 2425人阅读

摘要:未加载返回已加载返回类对象系统计时器的当前值纳秒父根链接一个指定的类由自定义类加载器重载体现了以上所述的类加载逻辑。为自定义类加载器提供了入口。

这周在看《深入理解Java虚拟机 JVM高级特性与最佳实践(高清完整版)》,就地取材写写第7章中提到的类加载器。以下源码截自java8。

delegation model

</>复制代码

  1. *

    The ClassLoader class uses a delegation model to search for

  2. * classes and resources. Each instance of ClassLoader has an
  3. * associated parent class loader. When requested to find a class or
  4. * resource, a ClassLoader instance will delegate the search for the
  5. * class or resource to its parent class loader before attempting to find the
  6. * class or resource itself. The virtual machine"s built-in class loader,
  7. * called the "bootstrap class loader", does not itself have a parent but may
  8. * serve as the parent of a ClassLoader instance.

截取自源码开篇注释。“delegation model”大部分文章译为“双亲委派模型”(个人感觉不是很贴切,“双”字很容易产生误解),阐述了一种类加载顺序关系。请求查找类或资源时,ClassLoader实例会先交给父级类加载器处理(组合实现,非继承),依次类推直到"bootstrap class loader",父级无法处理(在其范围内找不到对应类/资源)了再由自己加载。据说这样可以避免同名类引发的安全隐患。类加载顺序如下图。

loadClass --> findClass

</>复制代码

  1. /**
  2. * Loads the class with the specified binary name.
  3. * This method searches for classes in the same manner as the {@link
  4. * #loadClass(String, boolean)} method. It is invoked by the Java virtual
  5. * machine to resolve class references. Invoking this method is equivalent
  6. * to invoking {@link #loadClass(String, boolean) loadClass(name,
  7. * false)}.
  8. *
  9. * @param name
  10. * The binary name of the class
  11. *
  12. * @return The resulting Class object
  13. *
  14. * @throws ClassNotFoundException
  15. * If the class was not found
  16. */
  17. public Class loadClass(String name) throws ClassNotFoundException {
  18. return loadClass(name, false);
  19. }
  20. /**
  21. * Loads the class with the specified binary name. The
  22. * default implementation of this method searches for classes in the
  23. * following order:
  24. *
  25. *
    1. *
    2. *
    3. Invoke {@link #findLoadedClass(String)} to check if the class

    4. * has already been loaded.

    5. *
    6. *
    7. Invoke the {@link #loadClass(String) loadClass} method

    8. * on the parent class loader. If the parent is null the class
    9. * loader built-in to the virtual machine is used, instead.

    10. *
    11. *
    12. Invoke the {@link #findClass(String)} method to find the

    13. * class.

    14. *
    15. *
  26. *
  27. *

    If the class was found using the above steps, and the

  28. * resolve flag is true, this method will then invoke the {@link
  29. * #resolveClass(Class)} method on the resulting Class object.
  30. *
  31. *

    Subclasses of ClassLoader are encouraged to override {@link

  32. * #findClass(String)}, rather than this method.

  33. *
  34. *

    Unless overridden, this method synchronizes on the result of

  35. * {@link #getClassLoadingLock getClassLoadingLock} method
  36. * during the entire class loading process.
  37. *
  38. * @param name
  39. * The binary name of the class
  40. *
  41. * @param resolve
  42. * If true then resolve the class
  43. *
  44. * @return The resulting Class object
  45. *
  46. * @throws ClassNotFoundException
  47. * If the class could not be found
  48. */
  49. protected Class loadClass(String name, boolean resolve)
  50. throws ClassNotFoundException
  51. {
  52. synchronized (getClassLoadingLock(name)) {
  53. // First, check if the class has already been loaded
  54. // VM未加载返回null;已加载返回类对象
  55. Class c = findLoadedClass(name);
  56. if (c == null) {
  57. // 系统计时器的当前值(纳秒)
  58. long t0 = System.nanoTime();
  59. try {
  60. if (parent != null) {
  61. c = parent.loadClass(name, false); // 父
  62. } else {
  63. c = findBootstrapClassOrNull(name); // 根
  64. }
  65. } catch (ClassNotFoundException e) {
  66. // ClassNotFoundException thrown if class not found
  67. // from the non-null parent class loader
  68. }
  69. if (c == null) {
  70. // If still not found, then invoke findClass in order
  71. // to find the class.
  72. long t1 = System.nanoTime();
  73. c = findClass(name);
  74. // this is the defining class loader; record the stats
  75. sun.misc.PerfCounter.getParentDelegationTime().addTime(t1 - t0);
  76. sun.misc.PerfCounter.getFindClassTime().addElapsedTimeFrom(t1);
  77. sun.misc.PerfCounter.getFindClasses().increment();
  78. }
  79. }
  80. // 链接一个指定的类
  81. if (resolve) {
  82. resolveClass(c);
  83. }
  84. return c;
  85. }
  86. }
  87. /**
  88. * Finds the class with the specified binary name.
  89. * This method should be overridden by class loader implementations that
  90. * follow the delegation model for loading classes, and will be invoked by
  91. * the {@link #loadClass loadClass} method after checking the
  92. * parent class loader for the requested class. The default implementation
  93. * throws a ClassNotFoundException.
  94. *
  95. * @param name
  96. * The binary name of the class
  97. *
  98. * @return The resulting Class object
  99. *
  100. * @throws ClassNotFoundException
  101. * If the class could not be found
  102. *
  103. * @since 1.2
  104. */
  105. protected Class findClass(String name) throws ClassNotFoundException {
  106. throw new ClassNotFoundException(name);
  107. // 由自定义类加载器重载
  108. }

体现了以上所述的类加载逻辑。findClass为自定义类加载器提供了入口。

defineClass

</>复制代码

  1. /**
  2. * Converts an array of bytes into an instance of class Class,
  3. * with an optional ProtectionDomain. If the domain is
  4. * null, then a default domain will be assigned to the class as
  5. * specified in the documentation for {@link #defineClass(String, byte[],
  6. * int, int)}. Before the class can be used it must be resolved.
  7. *
  8. *

    The first class defined in a package determines the exact set of

  9. * certificates that all subsequent classes defined in that package must
  10. * contain. The set of certificates for a class is obtained from the
  11. * {@link java.security.CodeSource CodeSource} within the
  12. * ProtectionDomain of the class. Any classes added to that
  13. * package must contain the same set of certificates or a
  14. * SecurityException will be thrown. Note that if
  15. * name is null, this check is not performed.
  16. * You should always pass in the binary name of the
  17. * class you are defining as well as the bytes. This ensures that the
  18. * class you are defining is indeed the class you think it is.
  19. *
  20. *

    The specified name cannot begin with "java.", since

  21. * all classes in the "java.* packages can only be defined by the
  22. * bootstrap class loader. If name is not null, it
  23. * must be equal to the binary name of the class
  24. * specified by the byte array "b", otherwise a {@link
  25. * NoClassDefFoundError NoClassDefFoundError} will be thrown.

  26. *
  27. * @param name
  28. * The expected binary name of the class, or
  29. * null if not known
  30. *
  31. * @param b
  32. * The bytes that make up the class data. The bytes in positions
  33. * off through off+len-1 should have the format
  34. * of a valid class file as defined by
  35. * The Java™ Virtual Machine Specification.
  36. *
  37. * @param off
  38. * The start offset in b of the class data
  39. *
  40. * @param len
  41. * The length of the class data
  42. *
  43. * @param protectionDomain
  44. * The ProtectionDomain of the class
  45. *
  46. * @return The Class object created from the data,
  47. * and optional ProtectionDomain.
  48. *
  49. * @throws ClassFormatError
  50. * If the data did not contain a valid class
  51. *
  52. * @throws NoClassDefFoundError
  53. * If name is not equal to the binary
  54. * name of the class specified by b
  55. *
  56. * @throws IndexOutOfBoundsException
  57. * If either off or len is negative, or if
  58. * off+len is greater than b.length.
  59. *
  60. * @throws SecurityException
  61. * If an attempt is made to add this class to a package that
  62. * contains classes that were signed by a different set of
  63. * certificates than this class, or if name begins with
  64. * "java.".
  65. */
  66. protected final Class defineClass(String name, byte[] b, int off, int len,
  67. ProtectionDomain protectionDomain)
  68. throws ClassFormatError
  69. {
  70. protectionDomain = preDefineClass(name, protectionDomain);
  71. String source = defineClassSourceLocation(protectionDomain);
  72. Class c = defineClass1(name, b, off, len, protectionDomain, source);
  73. postDefineClass(c, protectionDomain);
  74. return c;
  75. }

defineClass:接收以字节数组表示的类字节码,并把它转换成 Class 实例,该方法转换一个类的同时,会先要求装载该类的父类以及实现的接口类。重写findClass将使用到。

</>复制代码

  1. public class Test {
  2. private static String link = "rebey.cn";
  3. static {
  4. System.out.println("welcome to: "+link);
  5. }
  6. public void print() {
  7. System.out.println(this.getClass().getClassLoader());
  8. }
  9. }

将这段java代码编译成.class文件(可通过javac指令),放在 了E:201706下。同时在我的测试项目下也有一个/201705/src/classLoader/Test.java,代码相同。区别就是一个有包名一个没有包名。如果class文件中源码包含package信息,届时可能会抛出java.lang.NoClassDefFoundError (wrong name)异常。

</>复制代码

  1. package classLoader;
  2. import java.io.ByteArrayOutputStream;
  3. import java.io.File;
  4. import java.io.FileInputStream;
  5. public class CustomClassLoader extends ClassLoader{
  6. private String basedir; // 需要该类加载器直接加载的类文件的基目录
  7. public CustomClassLoader(String basedir) {
  8. super(null);
  9. this.basedir = basedir;
  10. }
  11. protected Class findClass(String name) throws ClassNotFoundException {
  12. Class c = findLoadedClass(name);
  13. if (c == null) {
  14. byte[] bytes = loadClassData(name);
  15. if (bytes == null) {
  16. throw new ClassNotFoundException(name);
  17. }
  18. c = defineClass(name, bytes, 0, bytes.length);
  19. }
  20. return c;
  21. }
  22. // 摘自网络
  23. public byte[] loadClassData(String name) {
  24. try {
  25. name = name.replace(".", "//");
  26. FileInputStream is = new FileInputStream(new File(basedir + name + ".class"));
  27. ByteArrayOutputStream baos = new ByteArrayOutputStream();
  28. int b = 0;
  29. while ((b = is.read()) != -1) {
  30. baos.write(b);
  31. }
  32. is.close();
  33. return baos.toByteArray();
  34. } catch (Exception e) {
  35. e.printStackTrace();
  36. }
  37. return null;
  38. }
  39. }

编写自定义的类加载器,继承ClassLoader,重写了findClass方法,通过defineClass将读取的byte[]转为Class。然后通过以下main函数调用测试:

</>复制代码

  1. package classLoader;
  2. import java.lang.reflect.InvocationTargetException;
  3. import java.lang.reflect.Method;
  4. public class Loader {
  5. public static void main(String[] arg) throws NoSuchMethodException, ClassNotFoundException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
  6. // 走自定义加载器
  7. CustomClassLoader ccl = new CustomClassLoader("E://201706//");
  8. Class clazz = ccl.findClass("Test");
  9. Object obj = clazz.newInstance();
  10. Method method = clazz.getDeclaredMethod("print", null);
  11. method.invoke(obj, null);
  12. System.out.println("--------------我是分割线-------------------");
  13. // 走委派模式
  14. // 隐式类加载
  15. Test t1 = new Test();
  16. t1.print();
  17. System.out.println("--------------我是分割线-------------------");
  18. // 显式类加载
  19. Class t2 = Class.forName("classLoader.Test");
  20. Object obj2 = t2.newInstance();
  21. Method method2 = t2.getDeclaredMethod("print", null);
  22. method2.invoke(obj2, null);
  23. System.out.println("--------------我是分割线-------------------");
  24. Class t3 = Test.class;
  25. Object obj3 = t3.newInstance();
  26. Method method3 = t3.getDeclaredMethod("print", null);
  27. method3.invoke(obj3, null);
  28. }
  29. }
  30. 输出结果:
  31. welcome to: rebey.cn
  32. classLoader.CustomClassLoader@6d06d69c
  33. --------------我是分割线-------------------
  34. welcome to: rebey.cn
  35. sun.misc.Launcher$AppClassLoader@73d16e93
  36. --------------我是分割线-------------------
  37. sun.misc.Launcher$AppClassLoader@73d16e93
  38. --------------我是分割线-------------------
  39. sun.misc.Launcher$AppClassLoader@73d16e93

静态代码块随着类加载而执行,而且只会执行一次,所以这里t2、t3加载完成是并没有再输出。

说点什么

ClassLoader线程安全;

同个类加载器加载的.class类实例才相等;

Class.forName(xxx.xx.xx) 返回的是一个类, .newInstance() 后才创建实例对象 ;

Java.lang.Class对象是单实例的;

执行顺序:静态代码块 > 构造代码块 > 构造函数

</>复制代码

  1. 1、父类静态变量和静态代码块(先声明的先执行);

  2. 2、子类静态变量和静态代码块(先声明的先执行);

  3. 3、父类的变量和代码块(先声明的先执行);

  4. 4、父类的构造函数;

  5. 5、子类的变量和代码块(先声明的先执行);

  6. 6、子类的构造函数。

应用

通过自定义加载类,我们可以:

①加载指定路径的class,甚至是来自网络(自定义类加载器:从网上加载class到内存、实例化调用其中的方法)、DB(自定义的类装载器-从DB装载class(附上对类装载器的分析));

②给代码加密;(如何有效防止Java程序源码被人偷窥?)

③装逼(- -);

更多有意思的内容,欢迎访问笔者小站: rebey.cn

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/67249.html

相关文章

  • Java加载定义

    摘要:自定义类加载器示例代码类加载器获取的字节流字节流解密被加载的类测试代码以上代码,展示了自定义类加载器加载类的方法。这就需要自定义类加载器,以便对加载的类库进行隔离,否则会出现问题对于非的文件,需要转为类,就需要自定义类加载器。 Java类加载器的作用是寻找类文件,然后加载Class字节码到JVM内存中,链接(验证、准备、解析)并初始化,最终形成可以被虚拟机直接使用的Java类型。sho...

    hiyang 评论0 收藏0
  • Java加载机制

    摘要:当前类加载器和所有父类加载器都无法加载该类时,抛出异常。加载两份相同的对象的情况和不属于父子类加载器关系,并且各自都加载了同一个类。类加载机制与接口当虚拟机初始化一个类时,不会初始化该类实现的接口。 类加载机制 概念 类加载器把class文件中的二进制数据读入到内存中,存放在方法区,然后在堆区创建一个java.lang.Class对象,用来封装类在方法区内的数据结构。 1、加载: 查...

    aaron 评论0 收藏0
  • 加载以及双亲委派模型

    摘要:宗主引导类加载器。双亲委派模型是如何使用的我们在自定义加载器中查找是否有需要加载的文件,如果已经加载过,直接返回字节码。 作者:毕来生微信:878799579 1、小故事理解类加载器以及双亲委派模型 首先我们来描述一个小说场景,通过这个场景在去理解我们相关的类加载器的执行以及双亲委派模型。 上古时代有逍遥派和万魔宗两个宗派,互相对立。逍遥派比万魔门更加强势。巅峰战力更高。 有一天万魔宗...

    曹金海 评论0 收藏0
  • Java加载详解

    摘要:当一个文件是通过网络传输并且可能会进行相应的加密操作时,需要先对文件进行相应的解密后再加载到内存中,这种情况下也需要编写自定义的并实现相应的逻辑 Java虚拟机中的类加载有三大步骤:,链接,初始化.其中加载是指查找字节流(也就是由Java编译器生成的class文件)并据此创建类的过程,这中间我们需要借助类加载器来查找字节流. Java虚拟机默认类加载器 Java虚拟机提供了3种类加载器...

    Baaaan 评论0 收藏0
  • JVM加载过程 & 双亲委派模型

    摘要:类加载过程双亲委派模型声明文章均为本人技术笔记,转载请注明出处类加载过程类加载机制将类描述数据从文件中加载到内存,并对数据进行,解析和初始化,最终形成被直接使用的类型。深入理解虚拟机高级特性与最佳实践加载加载阶段由类加载器负责,过程见类加载 JVM类加载过程 & 双亲委派模型 声明 文章均为本人技术笔记,转载请注明出处https://segmentfault.com/u/yzwall ...

    happen 评论0 收藏0
  • 定义加载-从.class和.jar中读取

    摘要:在没有指定自定义类加载器的情况下,这就是程序的默认加载器。自定义类加载器双亲委派模型避免由于字节码被多次加载。首先自定义类加载器,最重要的就是先继承这个类。 一. 类加载器 JVM中的类加载器:在jvm中,存在两种类加载器,a) Boostrap ClassLoader:这个是由c++实现的,所以在方法区并没有Class对象的实例存在。用于加载JAVA_HOME/bin目录...

    Jackwoo 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<