Martin Braun Martin Braun - 1 year ago 79
Android Question

Compile .java Code on an Android device from within code [API]?

Here is what I want to achieve:

I am building an Android-Application which needs to be plugin-aware. What I need to do is downloading .java files from a Web-Server and then compile them at runtime within my application and then load it into the classpath. I want to use Java because of the ease of use because I can use the plugin objects just like my stock ones.

I've seen's way of compiling but that's not available on DalvikVM. What are the best alternatives to that (that work in a similar way)?


I am using .bsh-script now. This works like a charm on a JVM and should work on an Android device (which I will test next):

package de.hotware.beanshell.test;

import bsh.EvalError;
import bsh.Interpreter;

public class BeanShellTest {

public static interface InterfaceTest {

public void sayHello();


public static void main(String[] args) {
try {
Interpreter interpreter = new Interpreter();
InterfaceTest res = (InterfaceTest) interpreter.eval("import de.hotware.beanshell.test.BeanShellTest.InterfaceTest;" +
"new InterfaceTest() {" +
"public void sayHello() { System.out.println(\"hello\");}" +
} catch(EvalError e) {

public void test() {



Answer Source

You need to do two things:

  1. Everything you would do if you were running inside a JVM. Download the source, compile it into .class files with javac or equivalent.
  2. Convert the class files to DEX format. This would mean running the dx program on the device, which is doable, but it can be a bit memory-hungry, especially for larger programs.

Once you've done that, you can use DexClassLoader to load the code from the DEX file.

All things considered, I think you're better off with BeanShell.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download