How to load a Java class dynamically on android/dalvik?

The question:

I’m wondering if and how one can load dex or class files dynamically
in dalvik, some quick’n’dirty test function I wrote was this:

    public void testLoader() { 
            InputStream in; 
            int len; 
            byte[] data = new byte[2048]; 
            try { 
                    in = context.getAssets().open("f.dex"); 
                    len =; 
                    DexFile d; 
                    Class c = defineClass("net.webvm.FooImpl", data, 0, len); 
                    Foo foo = (Foo)c.newInstance(); 
            } catch (IOException e1) { 
                    // TODO Auto-generated catch block 
            } catch (IllegalAccessException e) { 
                    // TODO Auto-generated catch block 
            } catch (InstantiationException e) { 
                    // TODO Auto-generated catch block 

whereas the Foo interface is this

    public interface Foo { 
            int get42(); 

and f.dex contains some dx’ed implementation of that interface:

    public class FooImpl implements Foo { 
            public int get42() { 
                    return 42; 

The above test driver throws at defineClass() and it doesn’t
work and I investigated the dalvik code and found this:

So I’m wondering if anyone can enlighten me if this is possible in
some other way or not supposed to be possible. If it is not possible,
can anyone provide reasons why this is not possible?

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

There’s an example of DexClassLoader in the Dalvik test suite. It accesses the classloader reflectively, but if you’re building against the Android SDK you can just do this:

String jarFile = "path/to/jarfile.jar";
DexClassLoader classLoader = new DexClassLoader(
    jarFile, "/tmp", null, getClass().getClassLoader());
Class<?> myClass = classLoader.loadClass("MyClass");

For this to work, the jar file should contain an entry named classes.dex. You can create such a jar with the dx tool that ships with your SDK.

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment