Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to execute a Java code string at runtime in Android?

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

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

It is not java script and I want to run a java code.

Is it possible? If yes how?

I have studied links like this. But they are questions about JVM not Android Dalvik.

like image 460
Bobs Avatar asked Mar 27 '13 10:03

Bobs


People also ask

Can you code in Java in Android Studio?

Android Studio helps you to create new Java classes; enumeration and singleton classes; and interface and annotation types based on file templates. To create a new Java class or type, follow these steps: In the Project window, right-click a Java file or folder, and select New > Java Class.

Does Android run Java natively?

Android uses the Java Language and NOT the Java Virtual Machine, there is a big difference, it even uses its own byte code format.


1 Answers

You can try BeanShell! It's super easy and works also on android. Just build your app with 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 production app may be security risk, especially if your app interacts with users data / files.

like image 199
user1557434 Avatar answered Oct 21 '22 07:10

user1557434