SoFunction
Updated on 2025-03-11

A simple explanation of the class loader DexClassLoader in Android development

Introduction
"ClassLoader", as the name implies, is used to dynamically load class files. There is a ClassLoader class in the standard Java SDK. With this class, you can load the required class files, provided that the ClassLoader class initialization must define the path to the class file.

The difference between class files referenced by the import keyword and ClassLoader dynamically loaded classes:

Two characteristics of import reference class:

1. Must exist locally. When the program runs this class, the internal class loader will automatically load the class.

2. The compilation must be on site, otherwise the compilation process will not be compiled normally because the referenced file cannot be found.

The characteristics of classLoader are just the opposite of import, and are more free and flexible.

Each ClassLoader must have a parent ClassLoader. When loading the Class file, the child ClassLoader will first request its parent ClassLoader to load the file. Only when its parent ClassLoader cannot find the file, the child ClassLoader will inherit and load the class. This is a security mechanism. For Android, the final apk file contains a file of type dex. The dex file repackages the class file. The packaging rules are not simply compressed, but completely optimize various function tables and variable tables inside the class file to generate a new file, namely the dex file. Therefore, loading this special Class file requires a special class loader, DexClassLoader.

The class loader involved in Java is the ClassLoader class. The class we need can be loaded through the () method, thereby realizing the requirement of dynamically loading the class library at runtime. However, it is not feasible to use ClassLoader directly in Android, because ClassLoader loads the Java bytecode file, while Dex format bytecode is used in Android. For this reason, android provides a DexClassLoader class to complete the requirement of dynamic loading of apk.

Example
The following is a simple example to illustrate the use of the DexClassLoader class. This example involves two knowledge points: cross-package resource fetching & reflection call methods. First, build a Client project. This project is very simple, with only a simple layout and a method of sayingHello().

public class Main extends Activity {
 
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    (savedInstanceState);
    ();
  }
   
  @SuppressWarnings("unused")
  private void sayHello(String msg){
    ("mmtag",msg);
  }
   
}

Then create another project, in which the view in the client project is called and the sayHello() method is called. This class mainly involves the use of the DexClassLoader class.

package ;
 
import ;
import ;
import ;
 
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
 
public class MainActivity extends Activity {
 
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    (savedInstanceState);
    setContentView(.activity_main);
    useDexClassLoader();
  }
 
  @SuppressLint("NewApi")
  public void useDexClassLoader() {
 
    Intent mIntent = new Intent();
    ("",
        "");
    PackageManager pm = ();
    List<ResolveInfo> mList = (mIntent,
        PackageManager.MATCH_DEFAULT_ONLY);
    ResolveInfo info = (0);
     
    String apkPath = ;
    String optPath = ().getAbsolutePath();
    String libPath = ;
     
    DexClassLoader clsLoader = new DexClassLoader(apkPath, optPath,
        libPath, ().getClassLoader());
    try {
 
      Class cls = clsLoader
          .loadClass("");
      Object obj = ();
      Method invokeMethod = ("sayHello",
          new Class[] {  });
      (true);
      (obj, "hello world,DexClassLoader");
 
    } catch (Exception e) {
      ();
    }
  }
}


The result is:

I/dex2oat (20250): dex2oat took 1.547s (threads: 4)
 
D/mmtag  (20229): hello world,DexClassLoader
 
D/OpenGLRenderer(20229): Render dirty regions requested: tru

This successfully calls other methods in the apk.