ClassLoader use

foreword

In layman's terms, when the JVM needs a certain class, it loads the class into the JVM through the ClassLoader. Of course, the ClassLoader can also load files.

text

category

The JVM will generate three types of ClassLoader at runtime, namely Bootstrap ClassLoader, Extension ClassLoader and App ClassLoader.

Process

When a class is loaded into the JVM, the process it goes through is: Bootstrap ClassLoader->Extension ClassLoader->App ClassLoader. That is, the class is loaded by Bootstrap ClassLoade first. If it cannot be found, it will be loaded by Extension ClassLoader. Finally, if it cannot be found, it will be loaded by App ClassLoader.

App ClassLoader

There are three ways to get App ClassLoader:

  • this.getClass().getClassLoader()
  • Thread.currentThread().getContextClassLoader()
  • ClassLoader.getSystemClassLoader()

load class

After obtaining the ClassLoader, you can instantiate an object of a certain class in the following ways:

Class cls = classLoader.loadClass("com.silence.test");
Test test = (Test) cls.newInstance();

load file

After obtaining the ClassLoader, you can load the resource file in the following way (the relative path or the actual path can be used).
1. Method 1

InputStream is = classLoader.getResourceAsStream("com/silence/test.properties");

2. Method 2

ResourceBundle bundle = ResourceBundle.getBundle("com.silence.test");

Classloader debugging

You can debug which Jar package the loaded class originates from by adding -verbose:class to the startup parameter.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325853274&siteId=291194637