DexClassLoder - Didn't find class on path

1.6k views Asked by At

I'm trying to load classes from external JAR file placed on sdcard. Many people used DexClassLoader successfuly.

My steps:

1) Create classes.dex file from jar file:

dx --dex --output=classes.dex file.jar

2) Add generated classes.dex file to jar

3) Create DexClassLoader:

ClassLoader classLoader = new DexClassLoader(context.getDir("dex",
    Context.MODE_PRIVATE).getAbsolutePath(), jarfile.getAbsolutePath(), null,
    context.getClassLoader());

4) When I see what's in dex inside:

try {
  DexFile dx = DexFile.loadDex(jarFile.getAbsolutePath(), File.createTempFile("opt", "dex",
    context.getCacheDir()).getPath(), 0);
  // Print all classes in the DexFile
  for(Enumeration<String> classNames = dx.entries(); classNames.hasMoreElements();) {
    String className = classNames.nextElement();
    System.out.println("class: " + className);
  }
} catch (IOException e) {
    e.printStackTrace();
}

DexOpt: --- BEGIN 'file.jar' (bootstrap=0) ---
DexOpt: --- END 'file.jar' (success) ---
DEX prep '/mnt/sdcard/tmp/file.jar': unzip in 0ms, rewrite 83ms
class: com.test.TestClass

5) Load class:

Class<?> class = classLoader.loadClass("com.test.TestClass");

Here I get exception!:

java.lang.ClassNotFoundException: Didn't find class "com.test.TestClass" on path: /data/data/com.myapp/cache/app_dex

I see that it creates app_dex directory but it's empty.

Please, help!!!

2

There are 2 answers

0
nikman On

The only way I could load classes from jar is by DexFile class:

DexFile dexFile = DexFile.loadDex(jar.getAbsolutePath(),
    File.createTempFile("opt", "dex", context.getCacheDir()).getPath(), 0);
....
Class<?> currClass = dexFile.loadClass(className, context.getClassLoader());

Very interesting why I can't do this with DexClassLoader. Does anybody use it in Android 4.2.2 or 4.4.2 ? Thanks!

0
Vlad On

It seems you set incorrect order

ClassLoader classLoader = new DexClassLoader(context.getDir("dex",
Context.MODE_PRIVATE).getAbsolutePath(), jarfile.getAbsolutePath(), null,
context.getClassLoader());

replace first parameter with second

More info https://developer.android.com/reference/dalvik/system/DexClassLoader#public-constructors_1