Is it possible to execute a line of Java code at run time on Android?

I want to get a line of Java code from a user and execute it in Android. For example:

String strExecutable = " int var; var = 4 + 3" Object obj = aLibrary.eval(strExecutable); 

This is not a java script, and I want to run Java code.

Is it possible? If so, how?

I have studied links like. But these are questions about the JVM, not the Android Dalvik.

+8
source share
3 answers

You can try BeanShell ! It is super easy and also works on Android. Just create an application using the jar library.

 import bsh.Interpreter; private void runString(String code){ Interpreter interpreter = new Interpreter(); try { interpreter.set("context", this);//set any variable, you can refer to it directly from string interpreter.eval(code);//execute code } catch (Exception e){//handle exception e.printStackTrace(); } } 

But be careful! Using this in a production application can be a security risk, especially if your application interacts with user data / files.

+3
source

You can try something like this:

 // Code Execute, Khaled A Khunaifer, 27 March 2013 class CodeExcute { public static void execute (String[] commands, String[] headers) { // build commands into new java file try { FileWriter fstream = new FileWriter("Example.java"); BufferedWriter out = new BufferedWriter(fstream); out.write(""); for (String header : headers) out.append(header); out.append("class Example { public static void main(String args[]) { "); for (String cmd : commands) out.append(cmd); out.append(" } }"); out.close(); } catch (Exception e) { System.err.println("Error: " + e.getMessage()); } // set path, compile, & run try { Process tr = Runtime.getRuntime().exec( new String[]{ "java -cp .", "javac Example.java", "java Example" } ); } catch (Exception e) { System.err.println("Error: " + e.getMessage()); } } } 
+2
source

You can use JavaScript code and use Rhino Lib To Executed. use rhino

0
source

All Articles