Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 = in.read(data);                      in.close();                      DexFile d;                      Class c = defineClass("net.webvm.FooImpl", data, 0, len);                      Foo foo = (Foo)c.newInstance();              } catch (IOException e1) {                      // TODO Auto-generated catch block                      e1.printStackTrace();              } catch (IllegalAccessException e) {                      // TODO Auto-generated catch block                      e.printStackTrace();              } catch (InstantiationException e) {                      // TODO Auto-generated catch block                      e.printStackTrace();              }      }  

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:

http://www.google.com/codesearch/p?hl=en#atE6BTe41-M/vm/Jni.c&q=Jni.c...

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?

like image 695
anselm Avatar asked Jun 11 '10 11:06

anselm


People also ask

What is Java dynamic loading?

Dynamic loading is a technique for programmatically invoking the functions of a class loader at run time. Dynamic class loading is done when the name of the class is not known at compile time.


1 Answers

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.

like image 195
Jesse Wilson Avatar answered Sep 26 '22 12:09

Jesse Wilson