Methods of loading various resources (classes, files, Web resources) with ClassLoader in Java

Source: Internet
Author: User

Lassloader primarily serves the request of a class, when a class is required by the JVM, it requires the class according to the name, and then returns the class object of ClassLoader by ClassLoader.

ClassLoader is responsible for loading all of the resources (Class, file, image, byte stream from the network, etc.) of the system and loading the resources into the JVM through ClassLoader. Each class has a reference that points to its own classloader.

1. Ways to get ClassLoader

There are 3 ways to get ClassLoader:


    1. This.getClass.getClassLoader (); //Use the ClassLoader of the current class
    2. Thread.CurrentThread (). Getcontextclassloader (); //using the current thread's ClassLoader
    3. Classloader.getsystemclassloader ();  //Use the system ClassLoader, which is the ClassLoader used by the system's entry point.

Note: The system ClassLoader is not the same as the root ClassLoader. The system ClassLoader under the JVM is typically app ClassLoader.

2. Several ways to load resources with ClassLoader

All resources are loaded into the JVM via ClassLoader, so you can certainly use ClassLoader when loading resources, but you can also load them in some other way for different resources, for example, the class can be directly new, the file can be directly IO, etc.

Class 2.1 Loading mode

Suppose there are Class A and class b,a that need to instantiate B in their methods, there are 3 possible ways to load a class. For loading classes, the user needs to know the full name of Class B (including the package name, such as "com.alexia.b")

1. Using the Class static method Class.forName


    1. Class cls = Class.forName ("com.alexia.b");
    2. b b = (b) cls.newinstance ();

2. Using ClassLoader


    1. /* Step 1. Get ClassLoader */
    2. ClassLoader cl = This.getClass.getClassLoader (); //How to get ClassLoader reference 1
    3. /* Step 2. Load the class */
    4. Class cls = Cl.loadclass ("com.alexia.b"); //Use the first step to get the ClassLoader to load B
    5. /* Step 3. new instance */
    6. b b = (b) cls.newinstance (); //A class with B gets an instance of B

3. Direct NEW


    1. b b = new B ();

Note: Some people may think that we will choose the simplest 3rd way to load the class, the first two ways are completely superfluous.

Otherwise, the direct new approach is limited, for the simplest example: how does a class with a package name in Java refer to a class in the default package? Of course, this is because the class with the package name cannot directly refer to the class in the default package with new. The answer is to use the reflection mechanism, even if the class is loaded in the first way (see here for details). Also, creating instances of classes with new () and newinstance () is different, and the main differences are briefly described as follows:

From the JVM's point of view, when we use the keyword new to create a class, the class can not be loaded. However, when using the Newinstance () method, it is necessary to ensure that:

(1) This class has been loaded;

(2) This class is already linked (that is, allocating storage space for a static domain, and parsing all references to other classes created by the class if necessary). And the completion of the above two steps is exactly the static method of Class forname (), this static method calls the Startup class loader, that is, the loader loaded Javaapi.

As you can see, newinstance () actually breaks the new approach into two steps, that is, the class loading method is first called to load a category and then instantiated. The benefits of this step are obvious. We can get better flexibility when invoking the static Load method of class forname, providing a means of decoupling.

2.2 How files are loaded (e.g., configuration files, etc.)

Suppose in the Com.alexia.a class want to read the folder/com/alexia/config in the file sys.properties, read the file can pass absolute path or relative path, absolute path is simple, under Windows with the disk number, under UNIX under the "/ Start For a relative path, its relative value is relative to ClassLoader, because ClassLoader is a tree, so the relative path and any classloader on the ClassLoader tree can find the file relative to it, then the file can be found. There are three ways to load the file:

1. Read directly with IO stream


  1. /**
  2. * Assuming the current position is "c:/test", run A "Java com.aleixa.a" by executing the following command
  3. * 1. The absolute path can be used in the program, the absolute path under Windows begins with the disk number, and Unix starts with "/".
  4. * 2. You can also use a relative path with no "/" in front of the relative path
  5. * Because we execute the program under the "C:/test" directory, the program entry point is "c:/test" and the relative path is
  6. * is "com/alexia/config/sys.properties"
  7. * (in the example, the ClassLoader of the current program is the app Classloader,system ClassLoader = current
  8. * The ClassLoader of the program, the entry point is "C:/test")
  9. * For classloader trees, if the file is under JDK lib, or under JDK lib/ext, or in an environment variable,
  10. * Can be found by the relative path "Sys.properties", lib files are first found
  11. */
  12. File F = new file ("c:/test/com/aleixa/config/sys.properties"); //Use absolute path
  13. File F = new file ("Com/alexia/config/sys.properties"); Using relative paths
  14. InputStream is = new FileInputStream (f);

2. Using ClassLoader


  1. /**
  2. * Because there are 3 ways to get ClassLoader, the following 3 ClassLoader methods should be used to read the file
  3. * The path used is relative to the point relative to the ClassLoader, where only relative paths are used
  4. */
  5. InputStream is = null;
  6. is = This.getclass (). getClassLoader (). getResourceAsStream (
  7. "Com/alexia/config/sys.properties"); //Method 1
  8. is = Thread.CurrentThread (). Getcontextclassloader (). getResourceAsStream (
  9. "Com/alexia/config/sys.properties"); //Method 2
  10. is = Classloader.getsystemresourceasstream ("com/alexia/config/sys.properties"); Method 3

3. Using ResourceBundle


    1. ResourceBundle bundle = Resourcebundle.getboundle ("Com.alexia.config.sys");

This usage is usually used to load the user's profile, and for more detailed use of Resourcebunlde, refer to the other documentation.

Note: If it is a property profile, the content can also be read into the properties by Java.util.Properties.load (IS), which by default considers the encoding of IS iso-8859-1, If the configuration file is non-English, garbled problems may occur.

Summary: There are 3 ways to load files

1. Absolute path---> IO
2. Relative Path---> IO
---> ClassLoader
3. Resource Bundle---> ResourceBundle

2.3 How to load Web resources

You can also use ClassLoader to load resources in Web applications, but it is more common to use ServletContext, which is the web directory structure
Contextroot
|-JSP, HTML, image and many other files
|-[Web-inf]
|-Web
|-[lib] the jar file used by the Web
|-[Classes] class file

The user program is usually in the classes directory, if you want to read the classes directory files, you can use ClassLoader, if you want to read other files, generally use Servletcontext.getresource ().

If you use the Servletcontext.getresource (path) method, the path must begin with "/", the path is interpreted as relative to the Contextroot path, and the method to load the file here differs from ClassLoader, for example "/web-inf/ Web. xml ","/download/webexagent.rar "

Methods of loading various resources (classes, files, Web resources) with ClassLoader in Java

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.