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.
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.
Android uses the Java Language and NOT the Java Virtual Machine, there is a big difference, it even uses its own byte code format.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With