Dynamic code execution
For real Java code, this is possible using the JavaCompiler
interface. However, it's very inconvenient to use since it's just an interface to a real Java compiler that expects to compile entire class definitions found in files.
The easiest way to execute code supplied at runtime would be to use the Rhino JavaScript engine.
Both of these options have been only in Java 6, though I believe the scripting interface existed before, so you could use Rhino in an earlier JRE if you download and add it to the classpath.
What is wrong with this dynamic code execution?
The code fails / can't be compiled because it contains three issues:
- The method needs to be public
- The return value is not a
string
like specified - Missing semicolon in the method
Fix it like this to get it running:
var code = @"using System; public class Abc { public static string Get() { return System.DateTime.Now.ToString(); } }";
You should check the errors after compiling your code compile.Errors.
How do I execute dynamic code in a container?
- THIS IS A VERY BAD IDEA DO NOT DO IT
- You would want to run each snippet in a new container for maximum isolation.
Dynamic C# code execution
You didn't explicitly state if you're looking for guidance on implementing your own solution or what, but if you're open to using a third party utility then LINQPad is pretty much exactly what you're describing.
Dynamic code evaluation in scala
You could use either scala-lang
API for that or twitter-eval
. Here is the snippet of a simple use case of scala-lang
import scala.tools.nsc.Settings
import scala.tools.nsc.interpreter.IMain
object ScalaReflectEvaluator {
def evaluate() = {
val clazz = prepareClass
val settings = new Settings
settings.usejavacp.value = true
settings.deprecation.value = true
val eval = new IMain(settings)
val evaluated = eval.interpret(clazz)
val res = eval.valueOfTerm("res0").get.asInstanceOf[Int]
println(res) //yields 9
}
private def prepareClass: String = {
s"""
|val x = 4
|val y = 5
|x + y
|""".stripMargin
}
}
or with twitter:
import com.twitter.util.Eval
object TwitterUtilEvaluator {
def evaluate() = {
val clazz = prepareClass
val eval = new Eval
eval.apply[Int](clazz)
}
private def prepareClass: String = {
s"""
|val x = 4
|val y = 5
|x + y
|""".stripMargin
}
}
I am not able to compile it at the moment to check whether I have missed something but you should get the idea.
AWS Lambda execute dynamic code
eval works fine in Lambda. Remove the 'use strict' and it will work fine, outputting 10.
strict mode doesn't allow creating global variables, that's why you're getting the error.
A second option is to explicity add the function to the global context:
'use strict';
exports.handler = (event, context, callback) => {
var body = "global.test = function() { return 10; };";
console.log("body", body);
eval(body);
var result = test();
callback(null, result);
};
R: dynamic construction and execution of commands
You want to evaluate the parsed text:
> eval(parse(text="gray.colors(n=10)"))
[1] "#4D4D4D" "#6C6C6C" "#838383" "#969696" "#A7A7A7" "#B5B5B5" "#C3C3C3"
[8] "#CFCFCF" "#DBDBDB" "#E6E6E6"
Any text can be evaluated and run this way. Note that if this string can be set by a user and sent to a server there may be a way for them to run arbitrary code on your server. Make sure you validate the allowed palette functions on the server before running code from clients like this (search for "XKCD Bobby Tables" for more).
Another option is using do.call
, which works with character strings of function names:
> do.call("gray.colors",list(n=10))
[1] "#4D4D4D" "#6C6C6C" "#838383" "#969696" "#A7A7A7" "#B5B5B5" "#C3C3C3"
[8] "#CFCFCF" "#DBDBDB" "#E6E6E6"
and is probably less vulnerable to code injection vulnerabilities.
Related Topics
Getting the Inputstream from a Classpath Resource (Xml File)
Javabean Wrapping with Javafx Properties
Is Calling Static Methods via an Object "Bad Form"? Why
"Non-Static Variable This Cannot Be Referenced from a Static Context" When Creating an Object
How to Convert a Java Object (Bean) to Key-Value Pairs (And Vice Versa)
Java: How to Indent Xml Generated by Transformer
JPA Query Selecting Only Specific Columns Without Using Criteria Query
How to Make Lombok and Aspectj Work Together
In Java, How to Get the Difference in Seconds Between 2 Dates
How to Use Mockito When We Cannot Pass a Mock Object to an Instance of a Class
Checked VS Unchecked Exception
What Are the Best Use Cases for Akka Framework
Java Class.Cast() VS. Cast Operator
Best Way to Get Geo-Location in Java
How to Get Just the Parent Directory Name of a Specific File