How could I parse a string statement into code?
e.g.:
boolean isOnline = true;
boolean isConnected = true;
String statement = "isOnline && isConnected";
if(statement) // do something
How could I parse a string statement into code?
e.g.:
boolean isOnline = true;
boolean isConnected = true;
String statement = "isOnline && isConnected";
if(statement) // do something
try this:
boolean isOnline = true;
boolean isConnected = true;
String statement = "isOnline && isConnected";
String[] split = statement .split(" && ");
if(split.lenght > split[0].equals("isOnline") && split[1].equals("isConnected")){
// do something
}
I would suggest the following strategy depending your knowledge on how is structured your string expression.
1- Develop your own parser.
You will have to develop your own grammar. There is an ANTLR port on android : ANTLR and Android
Ie, you will get with your expression ("isOnline" && "isConnected")
2- Use reflexivity/introspection
Once the string is parsed, you could use reflexivity to translate field or method expression into a field or a method.
Ie, you will translate "isOnline" to isOnline and "isConnected" to isConnected
Good luck for this
The original Java has a built-in JavaCompiler class which would allow you to compile and load code that forms a complete valid .java file.
Android does not have this.
You could try to use some JavaScript engine written in Java (see, e.g., Android utilize V8 without WebView).
However, this would still not allow you to access local variables declared in your Java function. (With the reflection API, you would be able to read the values of class fields.)