How To Convert String To Runnable Code In Java
Janino is a popular choice for an on-demand-compiler. It's being used by many open source projects.
The usage is straight forward. The code
import org.codehaus.janino.ScriptEvaluator;
public class App {
public static void main(String[] args) throws Exception {
String x = "System.out.println(\"X\");"; //<-- dont forget the ; in the string here
ScriptEvaluator se = new ScriptEvaluator();
se.cook(x);
se.evaluate(new Object[0]);
}
}
prints x
.
As others have already pointed out, loading code from the database and executing it might be a bit risky.
How can I convert string to source code in python?
You can use eval()
function to evaluate Python source code.
Quoting the documentation:
eval(expression, globals=None, locals=None)
The arguments are a string and optional globals and locals. If provided, globals must be a dictionary. If provided, locals can be any mapping object.
What are the ways to convert a String into runnable code?
You can simple execute your code contained inside String using Quasiquotes(Experimental Module).
import scala.reflect.runtime.universe._
import scala.reflect.runtime.currentMirror
import scala.tools.reflect.ToolBox
// TO compile and run code we will use a ToolBox api.
val toolbox = currentMirror.mkToolBox()
// write your code starting with q and put it inside double quotes.
// NOTE : you will have to use triple quotes if you have any double quotes usage in your code.
val code1 = q"""new String("hello")"""
//compile and run your code.
val result1 = toolbox.compile(code1)()
// another example
val code2 = q"""
case class A(name:String,age:Int){
def f = (name,age)
}
val a = new A("Your Name",22)
a.f
"""
val result2 = toolbox.compile(code2)()
Output in REPL :
// Exiting paste mode, now interpreting.
import scala.reflect.runtime.universe._
import scala.reflect.runtime.currentMirror
import scala.tools.reflect.ToolBox
toolbox: scala.tools.reflect.ToolBox[reflect.runtime.universe.type] = scala.tools.reflect.ToolBoxFactory$ToolBoxImpl@69b34f89
code1: reflect.runtime.universe.Tree = new String("hello")
result1: Any = hello
code2: reflect.runtime.universe.Tree =
{
case class A extends scala.Product with scala.Serializable {
<caseaccessor> <paramaccessor> val name: String = _;
<caseaccessor> <paramaccessor> val age: Int = _;
def <init>(name: String, age: Int) = {
super.<init>();
()
};
def f = scala.Tuple2(name, age)
};
val a = new A("Your Name", 22);
a.f
}
result2: Any = (Your Name,22)
scala>
To learn more about Quasiquotes :
http://docs.scala-lang.org/overviews/quasiquotes/setup.html
How to convert a string to python code in python?
Yes, eval()
only evaluates expressions, not statements or suites (which comprise full Python programs).
You're looking for the exec()
function.
exec("for i in range(100):\n\tprint(i)")
However, do remember you usually don't need eval()
or exec()
, and especially you'll never want to exec()
or eval()
user input.
Related Topics
Why Does Runtime.Exec(String) Work for Some But Not All Commands
Java Class That Implements Map and Keeps Insertion Order
Java - Method Name Collision in Interface Implementation
Auto Errors Detection in Intellij Idea
Collect Successive Pairs from a Stream
Convert Date/Time for Given Timezone - Java
How to Execute Cmd Commands via Java
File Path to Resource in Our War/Web-Inf Folder
Is There a Concurrent List in Java's Jdk
How to Write a Custom JSON Deserializer for Gson
Why Do We Usually Use || Over |? What Is the Difference
Why Can't Overriding Methods Throw Exceptions Broader Than the Overridden Method
How Will Java Lambda Functions Be Compiled
How to Increase the Jvm Memory
Java Reading a File into an Arraylist
Java - Best Approach to Parse Huge (Extra Large) JSON File
Dynamic Spring Data JPA Repository Query with Arbitrary and Clauses