简体   繁体   English

为什么使用 ClassLoader 读取资源

[英]Why use a ClassLoader to read a resource

I encountered a case where I need to use ClassLoader:我遇到了需要使用ClassLoader的情况:

I have a XML file which specifies the configuration detail for sql, and I want to load it into a configuration class.我有一个 XML 文件,它指定了 sql 的配置详细信息,我想将它加载到配置 class 中。 The first step is to load what is in the XML into an Inputstream.第一步是将 XML 中的内容加载到 Inputstream 中。

public class Resources{
    public static InputStream getResourceAsStream(String path){
        InputStream resourceAsStream = Resources.class.getClassLoader().getResourceAsStream(path);
        return resourceAsStream;
    }
}

I only know vaguely what is a classloader: It loads classes into JVM.我只模糊地知道什么是类加载器:它将类加载到 JVM 中。 It is not clear to me at all why one would use classLoader here.我完全不清楚为什么要在这里使用 classLoader。 Can't we just read what is in path directly?我们不能直接读取路径中的内容吗? My guess is that this might have something to do with the timing of when one wants to load the resource.我的猜测是,这可能与想要加载资源的时间有关。

A project is composed of two things:一个项目由两部分组成:

  • Code compiled into.class file代码编译成.class文件
  • Ressources (any file such as properties, xml...)资源(任何文件,例如属性,xml...)

Then it is packaged.然后它被打包。 The packaging can be mainly:包装主要可以是:

  • a JAR一个 JAR
  • a directory一个目录

A ClassLoader is what is capable to access to packaged projects (jars, directories...). ClassLoader 能够访问打包的项目(jar、目录...)。 The main ClassLoader is accessing jars and directories specified in the classpath, but additional ClassLoader may be added at runtime.主 ClassLoader 正在访问 jars 和类路径中指定的目录,但可能会在运行时添加额外的 ClassLoader。 For example, on an application server, where you can deploy new packaged applications at runtime, for every application a ClassLoader will be created.例如,在应用程序服务器上,您可以在运行时部署新的打包应用程序,为每个应用程序创建一个 ClassLoader。

That's why, to access ressources from a packaged project, you need to use a ClassLoader (even the name is not clear about ressources).这就是为什么,要从打包的项目中访问资源,您需要使用 ClassLoader(即使资源的名称也不清楚)。 If you want to access a ressource packaged together with your class in the same project, you get the ClassLoader of your class so you are sure it can access the ressources of the same project.如果您想在同一个项目中访问与 class 一起打包的资源,您将获得 class 的 ClassLoader,这样您就可以确定它可以访问同一项目的资源。

The most typical ClassLoader is java.net.URLClassLoader, which takes a list of URLs (local or remote JARs, directories...) such as the classpath, and look into every URL to search for.class files or ressources files.最典型的 ClassLoader 是 java.net.URLClassLoader,它获取一个 URL 列表(本地或远程 JARs、目录...),例如 classpath,并查看每个 URL 以搜索 .ZA2F22ED4F8EBC402CBBDC 文件或 resssource DC 文件

To sum up, you can see a ClassLoader as a list of locations where to search files, either.class to load classes, or any other type of file as ressources.总而言之,您可以将 ClassLoader 视为搜索文件的位置列表,或者将.class 用于加载类,或者将任何其他类型的文件作为资源。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM