Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use a ClassLoader to read a resource

Tags:

java

I encountered a case where I need to use ClassLoader:

I have a XML file which specifies the configuration detail for sql, and I want to load it into a configuration class. The first step is to load what is in the XML into an 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. It is not clear to me at all why one would use classLoader here. 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.

like image 583
koch Avatar asked Oct 29 '25 14:10

koch


1 Answers

A project is composed of two things:

  • Code compiled into .class file
  • Ressources (any file such as properties, xml...)

Then it is packaged. The packaging can be mainly:

  • a JAR
  • a directory

A ClassLoader is what is capable to access to packaged projects (jars, directories...). The main ClassLoader is accessing jars and directories specified in the classpath, but additional ClassLoader may be added at runtime. For example, on an application server, where you can deploy new packaged applications at runtime, for every application a ClassLoader will be created.

That's why, to access ressources from a packaged project, you need to use a ClassLoader (even the name is not clear about ressources). 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.

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.

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.

like image 128
Zinc Avatar answered Nov 01 '25 03:11

Zinc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!