美文网首页
ClassLoader

ClassLoader

作者: 码而优则仕 | 来源:发表于2020-06-25 19:34 被阅读0次

ClassLoader

.Java源文件被Java编译器编译成.class字节码文件,ClassLoader负责从.class文件中读取字节码并转换成java.lang.Class类的实例(对应一个Java类),并存储在JVM内存中;结合反射通过Class类实例的 newInstance方法创建Class类实例对应的Java对象实例。

类加载器的职责:

1 根据类的名称找到或生成类对应的.class字节码文件

2 加载Java应用程序需要用到的资源,如:图片文件,配置文件,文件目录等

由于类加载器可以加载资源,所以可以通过类加载器获取到资源的信息,如资源的路径等

但是首先需要获取项目中加载类的加载器实例

如何在项目中获取当前类加载器:

Thread.currentThread().getContextClassLoader();

ClassLoader类获取指定路径资源的方法:

其中的name参数是 / 隔开的

The name of a resource is a '<tt>/</tt>'-separated path name that identifies the resource.

/**
 * Finds the resource with the given name.  A resource is some data
 * (images, audio, text, etc) that can be accessed by class code in a way
 * that is independent of the location of the code.
 *
 * <p> The name of a resource is a '<tt>/</tt>'-separated path name that
 * identifies the resource.
 *
 * <p> This method will first search the parent class loader for the
 * resource; if the parent is <tt>null</tt> the path of the class loader
 * built-in to the virtual machine is searched.  That failing, this method
 * will invoke {@link #findResource(String)} to find the resource.  </p>
 *
 * @apiNote When overriding this method it is recommended that an
 * implementation ensures that any delegation is consistent with the {@link
 * #getResources(java.lang.String) getResources(String)} method.
 *
 * @param  name
 *         The resource name
 *
 * @return  A <tt>URL</tt> object for reading the resource, or
 *          <tt>null</tt> if the resource could not be found or the invoker
 *          doesn't have adequate  privileges to get the resource.
 *
 * @since  1.1
 */
public URL getResource(String name) {
    URL url;
    if (parent != null) {
        url = parent.getResource(name);
    } else {
        url = getBootstrapResource(name);
    }
    if (url == null) {
        url = findResource(name);
    }
    return url;
}

相关文章

网友评论

      本文标题:ClassLoader

      本文链接:https://www.haomeiwen.com/subject/zzfefktx.html